简体   繁体   English

如何通过索引从列表框中获取文本?

[英]How do you get the text from a listbox by index?

I am trying to get text from an entry in my winForms ListBox by index, but I seem to be stumped. 我试图通过索引从我的winForms ListBox中的条目中获取文本,但我似乎很难过。 The only logical thing I can think of is: 我能想到的唯一合乎逻辑的是:

listBox.Items[index].ToString

But this does not return the desired result. 但这并没有返回预期的结果。

Does anyone know how to do this? 有谁知道如何做到这一点?

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;

使用此listBox.Items[index].Text

要通过索引从ListBox的项目中获取项目,请使用此方法

string item = listBox1.Items[0];

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

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