简体   繁体   English

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

[英]Get the ValueMember from a Listbox with SelectedValue?

i have a problem with the ValueMember. 我对ValueMember有问题。 I saved all my Items in a ListBox with two members: 我将所有项目保存在具有两个成员的ListBox中:

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

Now i create a loop to add my Obj into the list: 现在,我创建一个循环以将我的Obj添加到列表中:

   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: 至少,当我双击列表中的项目时,我会尝试获取用户ID:

    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. 这是问题SelectedValue为空。

i try to use SelectedItem but this just returns "MyItem", i try to get the complete object from the select but that dosent work. 我尝试使用SelectedItem,但是这只会返回“ MyItem”,我尝试从select中获取完整的对象,但是该方法很有效。

How can I get the ValuedMember "UserID" to the String selected? 如何获得ValuedMember的“ UserID”到所选的字符串?

much thanks for the Answers :) 非常感谢您的答案:)

The problem is caused by the way used to fill the Items collection. 该问题是由用于填充Items集合的方式引起的。 You are adding items one by one to the Items collection, instead you should set the DataSource of your ListBox to the listWithObjs variable 您正在将项一个接一个地添加到Items集合,而应该将ListBox的DataSource设置为listWithObjs变量

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 这是一个常见错误,但是如果您仔细阅读,将在MSDN页面上对ValueMember属性进行微妙的解释。

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. 一个String,代表DataSource属性值的单个属性名称,或者一个由句点分隔的属性名称的层次结构,解析为最终数据绑定对象的属性名称。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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