【问题标题】:C#: How to bind to ListBox DisplayMember and ValueMember result from class method?C#:如何从类方法绑定到 ListBox DisplayMember 和 ValueMember 结果?
【发布时间】:2014-08-03 09:40:24
【问题描述】:

我正在尝试创建具有键值对的 ListBox。我从类中获得的那些数据是从 getter 中提供的。

类:

public class myClass
{
    private int key;
    private string value;

    public myClass() { }

    public int GetKey()
    {
        return this.key;
    }

    public int GetValue()
    {
        return this.value;
    }
}

程序:

private List<myClass> myList;

public void Something()
{
    myList = new myList<myClass>();

    // code for fill myList

    this.myListBox.DataSource = myList;
    this.myListBox.DisplayMember = ??; // wanted something like myList.Items.GetValue()
    this.myListBox.ValueMember = ??; // wanted something like myList.Items.GetKey()
    this.myListBox.DataBind();
}

与本主题 [Cannot do key-value in listbox in C#] 类似,但我需要使用从方法返回值的类。

是否可以做一些简单的事情,或者我最好完全重新设计我的思路(和这个解决方案)?

感谢您的建议!

【问题讨论】:

  • myListlist&lt;myclass&gt;。因此,即使您可以说myList.Items.GetValue(),那么对于哪个特定的myclass 对象,它应该得到key/value?所以,这根本不合逻辑。
  • 谢谢。我是初学者,不知道如何创建自己的属性以及它有什么好处。现在它解决了我的问题!

标签: c# function listbox valuemember


【解决方案1】:

DisplayMemberValueMember 属性需要使用属性的名称(作为字符串)。你不能使用方法。所以你有两个选择。更改您的类以返回属性或创建一个派生自 myClass 的类,您可以在其中添加两个缺少的属性

public class myClass2 : myClass
{

    public myClass2() { }

    public int MyKey
    {
        get{ return base.GetKey();}
        set{ base.SetKey(value);}
    }

    public string MyValue
    {
        get{return base.GetValue();}
        set{base.SetValue(value);}
    }
}

现在您已经进行了这些更改,您可以使用新类更改您的列表(但修复初始化)

// Here you declare a list of myClass elements
private List<myClass2> myList;

public void Something()
{
    // Here you initialize a list of myClass elements
    myList = new List<myClass2>();

    // code for fill myList
    myList.Add(new myClass2() {MyKey = 1, MyValue = "Test"});

    myListBox.DataSource = myList;
    myListBox.DisplayMember = "MyKey"; // Just set the correct name of the properties 
    myListBox.ValueMember = "MyValue"; 
    this.myListBox.DataBind();         
}

【讨论】:

  • 你介意我说我爱你吗?我不知道如何制作自己的房产以及它实际上有什么好处。现在你解决了我的问题并教给我一些新的东西。这个属性的东西很棒,我肯定会更频繁地使用它。谢谢!
猜你喜欢
  • 2012-11-04
  • 2015-02-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-08-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多