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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/507354/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 06:07:17  来源:igfitidea点击:

How do I get at the listbox item's "key" in c# winforms app?

c#winformslistbox

提问by

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. The edits are then applied from the object list to an underlying file.

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

In ASP.Net assigning a different system value to a list item than the display text the user sees is trivial. 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.

在 ASP.Net 中,为列表项分配不同的系统值而不是用户看到的显示文本是微不足道的。在 winforms 应用程序中,您必须在稍微复杂一些(并且通常在 Internet 上不相关)的过程中设置每个项目的“Displaymember”和“Valuemember”。

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.

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

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. So how the hell do I get to the list item value?

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

采纳答案by Andy

Okay so the answer came as a result of Andy's answer, hence my upvoting that answer.

好的,所以答案是安迪的回答的结果,因此我赞成这个答案。

But when I created a little class and tried to cast the listitem into that class the program threw an exception.

但是当我创建一个小类并尝试将列表项转换为该类时,程序抛出了异常。

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.

最后给出了奇怪的简单答案。谢谢安迪的提示。

回答by Phaedrus

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";

回答by Andy

Using both the SelectedIndexChangedand SelectedValueChangeddidn't work for me - the ListBox'sSelectedValueproperty was always null. This surprised me, too.

使用SelectedIndexChangedSelectedValueChanged对我不起作用 - 该ListBox'sSelectedValue属性始终为空。这也让我很惊讶。

As a lame workaround, you could just pull the object out of the ListBoxdirectly, using the SelectedIndex:

作为一个蹩脚的解决方法,您可以ListBox使用以下命令直接将对象从 中拉出SelectedIndex

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

(Testis just a simple class with two properties - IDand Name).

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

It seems like there should be a better way, but if nothing else this should work.

似乎应该有更好的方法,但如果没有其他方法,这应该可行。

回答by Andy

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.
The secret is that Item method in C#, VBand others is an array, so to get a value of any Item you just have to write this:

当我搜索如何在 ListBox 中获取 Item 的值时,我最终来到这里,然后我想到了显而易见的事情。
秘密是在项目的方法C#VB和其他人是一个数组,所以让你只需要编写任何这项目的价值:

//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.

我希望我能帮到你们。这是对您的帖子最简单的回答。

回答by DarwinIcesurfer

I know this is a very old post, but I was unable to cast my list box items into a Dictionary item. 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;

回答by Moshtaf

A simple and clean way:

一个简单而干净的方法:

Add Item (include Key and Value) to 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 lsbListBoxNameis name of ListBox and the code is VB.NETyou can use This Online Toolto convent to C#.

lsbListBoxName是列表框的名称和代码是VB.NET,你可以使用这个在线工具来修道院到C#