C#: How to bind to ListBox DisplayMember and ValueMember result from class method?

风流意气都作罢 提交于 2019-12-11 20:14:23

问题


I'm trying to create ListBox where I will have key-value pair. Those data I got from class which provides them from getters.

Class:

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

    public myClass() { }

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

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

Program:

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();
}

It's similar to this topic [ Cannot do key-value in listbox in C# ] but I need to use class that returns values from methods.

Is it possible to do somewhat simple or I'd better rework my thought flow (and this solution) completely?

Thank you for advice!


回答1:


The DisplayMember and ValueMember properties require the name (as a string) of a property to be used. You can't use a method. So you have two options. Change you class to return properties or make a class derived from myClass where you could add the two missing properties

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);}
    }
}

Now that you have made these changes you could change your list with the new class (but fix the initialization)

// 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();         
}


来源:https://stackoverflow.com/questions/25103408/c-how-to-bind-to-listbox-displaymember-and-valuemember-result-from-class-metho

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!