从具有 SelectedValue 的列表框中获取 ValueMember?

Get the ValueMember from a Listbox with SelectedValue?

我对 ValueMember 有疑问。我将所有项目保存在一个包含两个成员的列表框中:

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

现在我创建一个循环来将我的对象添加到列表中:

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

至少,当我双击我的列表中的一个项目时,我会尝试获取 UserID:

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

问题是 SelectedValue 为空。

我尝试使用 SelectedItem,但这只是 returns "MyItem",我尝试从 select 中获取完整的对象,但那个 dosent 工作。

如何将 ValuedMember "UserID" 转换为 selected 字符串?

非常感谢您的回答:)

问题是由填充 Items 集合的方式引起的。您正在将项目一一添加到 Items 集合中,而应该将 ListBox 的 DataSource 设置为 listWithObjs 变量

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

当然去掉一个一个一个添加的循环

这是一个常见错误,但如果您仔细阅读,它会在 ValueMember 属性

的 MSDN 页面上以微妙的方式解释

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.