ListBox从索引中获取值

本文关键字:获取 索引 ListBox | 更新日期: 2023-09-27 18:14:19

我正在编写一个程序,您在列表框中插入一些数字,然后单击按钮应该从列表框中获取值,并检查它们是否为正或负,并在文本框中显示彼此的计数。我试着通过:string x = listBox1.Items[index].Value;获取值,但它似乎不起作用。

ListBox从索引中获取值

如果将项目添加到列表框中:

listBox1.Items.Add(textBox1.Text);

那么你可以从给定的索引中检索条目,如下所示:

string x = listBox1.Items[index];

索引器返回值,在这种情况下是字符串。您可能需要将其强制转换为string,因为索引器实际上返回的是对象—参见这里:ListBox.ObjectCollection.Item Property:

string x = (string)listBox1.Items[index];

你也可以试试

string s = (string)listbox1.Items.GetItemAt(index);

你需要将其强制转换为string因为它返回一个对象