如何在c#winforms应用程序中获取列表框项目的“密钥”?

我正在编写一个winforms应用程序,用户从列表框中选择一个项目并编辑构成关联对象一部分的一些数据。 然后将编辑从对象列表应用于基础文件。

在ASP.Net中,为列表项分配不同的系统值而不是用户看到的显示文本是微不足道的。 在winforms应用程序中,您必须将每个项目的“显示成员”和“有价值成员”设置为稍微复杂一些(而不是互联网上相关的)过程。

我已经这样做了。 在调试模式中,我已经确认每个项目现在都有一个值,即显示成员(用户看到的“友好”字符串)和一个键,值成员,用于保存要更新数据的哈希表对象的键。存在。

因此,当用户选择一个字符串来编辑程序时,应该将“密钥”传递给哈希表,将对象拉出并允许在其上进行编辑。

赶上?

我看不出任何明显的方式告诉程序查看项目的值成员。 我天真地期望它填充列表框的“SelectedValue”属性,但到目前为止这太简单了。 那我到底怎么去列表项值?

使用SelectedIndexChangedSelectedValueChanged对我来说都不起作用 – ListBox's SelectedValue属性始终为null。 这也让我感到惊讶。

作为一种蹩脚的解决方法,您可以使用SelectedIndex直接将对象拉出ListBox

 public Form1() { InitializeComponent(); this.listBox1.DisplayMember = "Name"; this.listBox1.ValueMember = "ID"; this.listBox1.Items.Add(new Test(1, "A")); this.listBox1.Items.Add(new Test(2, "B")); this.listBox1.Items.Add(new Test(3, "C")); this.listBox1.Items.Add(new Test(4, "D")); this.listBox1.Items.Add(new Test(5, "E")); } private void OnSelectedIndexChanged(object sender, EventArgs e) { if(-1 != this.listBox1.SelectedIndex) { Test t = this.listBox1.Items[this.listBox1.SelectedIndex] as Test; if(null != t) { this.textBox1.Text = t.Name; } } } 

Test只是一个带有两个属性的简单类IDName )。

似乎应该有更好的方法,但如果没有别的,这应该有效。

好的,所以答案来自Andy的答案,因此我对这个答案的支持。

但是当我创建一个小类并试图将listitem强制转换为该类时,该程序抛出exception。

显而易见的exception告诉我程序无法将DictionaryEntry转换为我定义的类型的类。

所以我删除了代理类并重新定义了请求:

 DictionaryEntry de = (DictionaryEntry)listbox.SelectedItem; 
string htKey = de.Key.ToString();

这一切都很好。

最后简单的答案。 感谢Andy的暗示。

我知道这是一个非常古老的post,但是我无法将列表框项目转换为Dictionary项目。 这个解决方案适用于.NET 3.5 for Windows窗体。

 KeyValuePair kvp = (KeyValuePair)listBoxSystems.SelectedItem; string szValue = kvp.Value; 

尝试从ListBox1_SelectedValueChanged事件中抓取“ValueMember”。

 private void ListBox1_SelectedValueChanged(object sender, EventArgs e) { if (ListBox1.SelectedIndex != -1) { string orbit = ListBox1.SelectedValue.ToString(); } } ArrayList planets = new ArrayList(); planets.Add(new Planet("Mercury", "1")); planets.Add(new Planet("Venus", "2")); //Remember to set the Datasource ListBox1.DataSource = planets; //Name and Orbit are properties of the 'Planet' class ListBox1.DisplayMember = "Name"; ListBox1.ValueMember = "Orbit"; 

呵呵呵,当我在搜索如何获取ListBox中一个Item的值时,我最终到了这里,然后明显出现在我脑海中。 秘诀是c#,VB等中的Item方法是一个数组,所以要获得任何Item的值,你只需要写这个:

 ListBox1.Items[1].toString();//Get value of the #1 Item in the ListBox; 

要获取所有项目并将其放入文档或字符串中,只需执行以下操作:

 String Value; for(int c=0;c 

我希望我帮助你们。 这是您post最简单的答案。

简单干净的方式:

将项目(包括键和值)添加到ListBox:

 lsbListBoxName.Items.Insert(0, New ListItem("Item 1", 1)) lsbListBoxName.Items.Insert(0, New ListItem("Item 2", 2)) ... 

获取用户选择的项目:

 Private Sub lsbListBoxName_SelectedIndexChanged(sender As Object, e As EventArgs) Handles lsbListBoxName.SelectedIndexChanged Console.WriteLine(TryCast(lsbListBoxName.SelectedItem, ListItem).Text) Console.WriteLine(TryCast(lsbListBoxName.SelectedItem, ListItem).Value) End Sub 

lsbListBoxName是ListBox的名称,代码是VB.NET,你可以使用这个在线工具来修改C#