2

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!

Community
  • 1
  • 1
Andebaran
  • 35
  • 1
  • 1
  • 5
  • `myList` is a `list`. So even if you can say `myList.Items.GetValue()` then for which particular `myclass` object it should get `key/value`? so, it's not logical at all. – Rahul Aug 03 '14 at 09:46
  • Thank you. I'm begginer and didn't know how to create own properties and what it is good for. Now it solves my problem! – Andebaran Aug 03 '14 at 10:31

1 Answers1

7

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();         
}
Steve
  • 213,761
  • 22
  • 232
  • 286
  • Would you mind I say I love you? I Didn't know how to make my own properties and what it is actually good for. Now you solved my problem and teach me something new. This properties stuff is great, I will use it more often for sure. Thank you! – Andebaran Aug 03 '14 at 10:33