How do I get at the listbox item#39;s quot;keyquot; in c# winforms app?(如何获取列表框项目的“键?在 c# winforms 应用程序中?)
问题描述
我正在编写一个 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 应用程序中,您必须以稍微复杂(并且在 Internet 上不经常相关)的过程来设置每个项目的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.
捕获?
我看不到任何明显的方式告诉程序查看项目的值成员.我天真地期望它会填充列表框的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?
推荐答案
好的,答案是 Andy 的答案,因此我赞成这个答案.
Okay so the answer came as a result of Andy's answer, hence my upvoting that answer.
但是当我创建一个小类并尝试将 listitem 转换为该类时,程序抛出了异常.
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 应用程序中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何获取列表框项目的“键"?在 c# winforms 应用程序中?
基础教程推荐
- 为什么Flurl.Http DownloadFileAsync/Http客户端GetAsync需要 2022-09-30
- SSE 浮点算术是否可重现? 2022-01-01
- MS Visual Studio .NET 的替代品 2022-01-01
- 如何在 IDE 中获取 Xamarin Studio C# 输出? 2022-01-01
- 如何激活MC67中的红灯 2022-01-01
- 将 XML 转换为通用列表 2022-01-01
- rabbitmq 的 REST API 2022-01-01
- 有没有办法忽略 2GB 文件上传的 maxRequestLength 限制? 2022-01-01
- 将 Office 安装到 Windows 容器 (servercore:ltsc2019) 失败,错误代码为 17002 2022-01-01
- c# Math.Sqrt 实现 2022-01-01