无法正常显示列表框项目 [英] listbox items not displaying properly

查看:123
本文介绍了无法正常显示列表框项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个列表框和我添加到列表框中,这样我可以检索从不同则显示的成员中所选项目的值ListItem对象。

I have a listbox and a ListItem object which I am adding to the listbox so that I can retrieve a value from the selected item which is different then the displayed member.

class ListItem
{
    public string DisplayMember;
    public string ValueMember;
    public ListItem(string n,string v){
         DisplayMember = n;
         ValueMember = v;
    }
}


public CompareTimeFramesForm()
{
    InitializeComponent();           
    listBox1.Items.Add(new ListItem("# of Bookings", null));
    listBox1.Items.Add(new ListItem("People", "guaranteed_count"));
}

这是一个仅供参考的WinForm。
我遇到的问题是,在实际的列表框中显示的项目有而不是我想的字符串,显示在列表项构造函数的第一个参数的对象。
它看起来像 Bookings.Helpers.ListItem 而不是

This is a winform FYI. The problem I am having is the item shown in the actual listbox has the object rather then the string I would like to be displayed in the first argument of the ListItem constructor. It looks like Bookings.Helpers.ListItem rather then "# of Bookings"

在设计师预订的#我改变了DisplayMember属性到的DisplayMember和它不工作

In the designer I changed the displayMember property to DisplayMember and its not working.

推荐答案

从MSDN:

当一个对象被添加到列表框,控制,除非在DisplayMember属性指定对象中的成员名称使用的对象的ToString方法定义的文本。

When an object is being added to the ListBox, the control uses the text defined in the ToString method of the object unless a member name within the object is specified in the DisplayMember property.

的ListBox 将项目转换为字符串调用的ToString( )。在你的情况,你只需要改变你的列表项类是这样的:

ListBox will convert item to string calling ToString(). In your case you just need to change your ListItem class like this:

class ListItem
{
    public string DisplayMember;
    public string ValueMember;

    public ListItem(string n,string v) {
         DisplayMember = n;
         ValueMember = v;
    }

    public override string ToString() {
        return DisplayMember;
    }
}



作为替代方案,你可以本身的的DisplayMember 属性(在设计或代码)使用你的财产(你叫该财产的DisplayMember ,但它的名字是免费的,因为它必须被指定它不使用任何约定):

As alternative you can se the DisplayMember property (in designer or with code) to use your property (you called that property DisplayMember but its name is free because it must be specified and it doesn't use any convention):

listBox1.DisplayMember = "DisplayMember";

这篇关于无法正常显示列表框项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆