如何获取在列表框项目的"键"在C#WinForms应用程序? [英] How do I get at the listbox item's "key" in c# winforms app?
问题描述
我写一个WinForms应用程序中,用户从列表框中选择一个项目和编辑,形成一个关联对象的一部分的一些数据。该编辑,然后从对象列表到底层文件的应用。
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.
在ASP.Net比用户看到的是文本显示列表项分配不同的系统值不重要的。在WinForms应用程序,你必须设置的DisplayMember,而在一个稍微更复杂(在互联网上不是经常相关的)过程中每个项目的Valuemember。
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.
这个我已经做了。在调试模式下我已经证实,每个项目现在有一个值是显示屏部件(友好的字符串用户看到)和一个键,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.
因此,当用户拿起一个字符串编辑程序应通过钥匙的哈希表,猛拉了对象,并允许编辑发生在它
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.
美中不足的?
我看不到告诉节目看的任何明显的方法项目的valuemember。我天真地期望它填充列表框中的的SelectedValue属性,但是这将是迄今为止太简单了。那么到底如何才能获得到列表项的价值?
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?
推荐答案
好了,所以答案之际,刘德华的回答的结果,因此,我upvoting这个问题的答案。
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.
说明问题的异常告诉我,程序无法投出的DictionaryEntry成一个类我已经定义的类型。
Revealingly the exception told me that the program could not cast a DictionaryEntry into a class of the type I had defined.
所以我删除了代理类和重新定义的要求这样的:
So I deleted the proxy class and reframed the request thus:
DictionaryEntry de = (DictionaryEntry)listbox.SelectedItem;
string htKey = de.Key.ToString();
和这一切都很好。
在年底奇怪的是简单的答案。谢谢你的提示安迪。
Bizarrely simple answer in the end. Thanks for the hint Andy.
这篇关于如何获取在列表框项目的"键"在C#WinForms应用程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!