简体   繁体   English

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

[英]How do I get at the listbox item's “key” in c# winforms app?

I am writing a winforms app in which a user selects an item from a listbox and edits some data that forms part of an associated object. 我正在编写一个winforms应用程序,其中用户从列表框中选择一个项目并编辑构成关联对象一部分的一些数据。 The edits are then applied from the object list to an underlying file. 然后将编辑从对象列表应用到基础文件。

In ASP.Net assigning a different system value to a list item than the display text the user sees is trivial. 在ASP.Net中,为列表项分配不同的系统值而不是用户看到的显示文本是微不足道的。 In a winforms app you have to set the "Displaymember" and the "Valuemember" of each item in a slightly more complicated (and not oft related on the internet) process. 在winforms应用程序中,您必须将每个项目的“显示成员”和“有价值成员”设置为稍微复杂一些(而不是在互联网上相关)过程。

This I have done. 我已经这样做了。 In debug mode I have confirmed that every item now has a value which is the display member (a "friendly" string that the user sees) and a key, the valuemember, which holds the key to a hashtable object where the data to be updated exists. 在调试模式中,我已经确认每个项目现在都有一个值,即显示成员(用户看到的“友好”字符串)和一个键值value,它将键保存到要更新数据的哈希表对象中存在。

So when a user picks a string to edit the program should pass the "key" to the hashtable, yank out the object and allow editing to take place upon it. 因此,当用户选择一个字符串来编辑程序时,应该将“密钥”传递给哈希表,将对象拉出并允许在其上进行编辑。

The catch? 抓到了吗?

I can't see any obvious way of telling the program to look at the item's valuemember. 我看不出任何明显的方式告诉程序查看项目的值成员。 I naively expected it to populate the list box's "SelectedValue" property, but that would be too simple by far. 我天真地期望它填充列表框的“SelectedValue”属性,但到目前为止这太简单了。 So how the hell do I get to the list item value? 那我到底怎么去列表项值?

Using both the SelectedIndexChanged and SelectedValueChanged didn't work for me - the ListBox's SelectedValue property was always null. 使用SelectedIndexChangedSelectedValueChanged对我来说都不起作用 - ListBox's SelectedValue属性始终为null。 This surprised me, too. 这也让我感到惊讶。

As a lame workaround, you could just pull the object out of the ListBox directly, using the SelectedIndex : 作为一种蹩脚的解决方法,您可以使用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 is just a simple class with two properties - ID and Name ). Test只是一个带有两个属性的简单类IDName )。

It seems like there should be a better way, but if nothing else this should work. 似乎应该有一个更好的方法,但如果没有别的,这应该工作。

Okay so the answer came as a result of Andy's answer, hence my upvoting that answer. 好的,所以答案来自Andy的回答,因此我的回答是正确的。

But when I created a little class and tried to cast the listitem into that class the program threw an exception. 但是当我创建一个小类并试图将listitem强制转换为该类时,该程序抛出异常。

Revealingly the exception told me that the program could not cast a DictionaryEntry into a class of the type I had defined. 显而易见的异常告诉我程序无法将DictionaryEntry转换为我定义的类型。

So I deleted the proxy class and reframed the request thus: 所以我删除了代理类并重新定义了请求:

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

And it's all good. 这一切都很好。

Bizarrely simple answer in the end. 最后简单的答案。 Thanks for the hint Andy. 感谢Andy的暗示。

I know this is a very old post, but I was unable to cast my list box items into a Dictionary item. 我知道这是一个非常古老的帖子,但我无法将列表框项目转换为Dictionary项目。 This solution worked for me in .NET 3.5 for windows forms. 这个解决方案适用于.NET 3.5 for Windows窗体。

KeyValuePair<int, string> kvp = (KeyValuePair<int, string>)listBoxSystems.SelectedItem;
string szValue = kvp.Value;

Try grabbing the "ValueMember" from within the ListBox1_SelectedValueChanged event. 尝试从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";

A simple and clean way: 简单干净的方式:

Add Item (include Key and Value) to ListBox: 将项目(包括键和值)添加到ListBox:

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


Get Item on user selection: 获取用户选择的项目:

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

the lsbListBoxName is name of ListBox and the code is VB.NET you can use This Online Tool to convent to C# . lsbListBoxName是ListBox的名称,代码是VB.NET,你可以使用这个在线工具来修改C#

I ended up here when I was searching how to get the value of an Item in ListBox, then the obvious came to my mind. 当我在搜索如何获取ListBox中的Item的值时,我最终到了这里,然后明显出现在我脑海中。
The secret is that Item method in C# , VB and others is an array, so to get a value of any Item you just have to write this: 秘诀是C#VB等中的Item方法是一个数组,所以要获得任何Item的值,你只需要写这个:

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

To get all the Items and put into a document or to a string, just do a for like this: 要获取所有项目并将其放入文档或字符串中,只需执行以下操作:

string Value;
for (int c = 0; c < ListBox1.Items.Count; c++)  {
    Value = Value + ListBox1.Items[c].toString();
}

I hope I helped you guys out. 我希望我能帮助你们。 This is the most simple answer to your post. 这是您帖子最简单的答案。

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

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