C# 如何通过索引从列表框中获取文本?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11370452/
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
How do you get the text from a listbox by index?
提问by
I am trying to get text from an entry in my winForms ListBox by index, but I seem to be stumped. The only logical thing I can think of is:
我试图通过索引从我的 winForms ListBox 中的条目中获取文本,但我似乎被难住了。我能想到的唯一合乎逻辑的事情是:
listBox.Items[index].ToString
But this does not return the desired result.
但这不会返回所需的结果。
Does anyone know how to do this?
有谁知道如何做到这一点?
采纳答案by Eric J.
What do you have in your Listbox?
你的列表框中有什么?
If there are string values in the listbox, your code is correct except for missing braces:
如果列表框中有字符串值,则除了缺少大括号外,您的代码是正确的:
string value = listBox.Items[index].ToString();
If the things in the listbox are some sort of object, you may need to override ToString() to get the desired result, or cast the thing you get out of the listbox to the desired type and then access an appropriate property.
如果列表框中的事物是某种对象,您可能需要重写 ToString() 以获得所需的结果,或者将您从列表框中得到的事物转换为所需的类型,然后访问适当的属性。
Example:
例子:
MyClass my = (MyClass)listBox.Items[index];
string value = my.SomePropertyOfMyClass;
回答by burning_LEGION
use this listBox.Items[index].Text
用这个 listBox.Items[index].Text
回答by HatSoft
To get the item from a ListBox's items by index please use this way
要按索引从 ListBox 的项目中获取项目,请使用这种方式
string item = listBox1.Items[0];

