简体   繁体   中英

Get the ValueMember from a Listbox with SelectedValue?

i have a problem with the ValueMember. I saved all my Items in a ListBox with two members:

listBox1.ValueMember = "userId";
listBox1.DisplayMember = "userName";

Now i create a loop to add my Obj into the list:

   foreach (var tempItem in listWithObjs)
   {
        MyItem testItem = new MyItem();
        testItem.userID = tempitem;//userID and userName are Strings the content is not very important i think
        testItem.userName = item.Split('\\').Last();
        listBox1.Items.Add(testItem);
    }

at least, I try to get the UserID when I double Click on an Item of my List:

    private void listBox1_DoubleClick(object sender, EventArgs e)
    {
        var selected = listBox1.SelectedValue; //SelectedValue is null
        label1.Text = Convert.ToString(selected);
    }

and here is the problem SelectedValue is null.

i try to use SelectedItem but this just returns "MyItem", i try to get the complete object from the select but that dosent work.

How can I get the ValuedMember "UserID" to the String selected?

much thanks for the Answers :)

The problem is caused by the way used to fill the Items collection. You are adding items one by one to the Items collection, instead you should set the DataSource of your ListBox to the listWithObjs variable

listBox1.ValueMember = "userId";
listBox1.DisplayMember = "userName";
listBox1.DataSource = listWithObjs;

Of course remove the loop that adds the items one by one

This is a common mistake, but if you read carefully it is explained in a subtle way on MSDN page for the ValueMember property

A String representing a single property name of the DataSource property value, or a hierarchy of period-delimited property names that resolves to a property name of the final data-bound object.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM