按索引获取列表框项的值

tza*_*zam 13 .net c# combobox listbox winforms

这一定很容易,但我被卡住了.我有一个带有X项的listBox.每个项目都有一个文本描述(出现在listBox中)及其值(数字).我希望能够使用项目的索引号获取项目的value属性.

小智 13

这将是

String MyStr = ListBox.items[5].ToString();
Run Code Online (Sandbox Code Playgroud)


Rez*_*aei 9

在这里,我甚至看不到这个问题的单一正确答案(在WinForms标签中),并且这种常见问题很奇怪.

一个项ListBox控制可以是DataRowView,复杂对象,匿名类型,原发性类型和其他类型.项目的基础价值应根据基础计算ValueMember.

ListBoxcontrol有一个GetItemText帮助您获取项目文本的控件,无论您添加为项目的对象类型如何.它真的需要这样的GetItemValue方法.

GetItemValue扩展方法

我们可以创建GetItemValue 扩展方法来获取项目值,其工作方式如下GetItemText:

using System;
using System.Windows.Forms;
using System.ComponentModel;
public static class ListControlExtensions
{
    public static object GetItemValue(this ListControl list, object item)
    {
        if (item == null)
            throw new ArgumentNullException("item");

        if (string.IsNullOrEmpty(list.ValueMember))
            return item;

        var property = TypeDescriptor.GetProperties(item)[list.ValueMember];
        if (property == null)
            throw new ArgumentException(
                string.Format("item doesn't contain '{0}' property or column.",
                list.ValueMember));
        return property.GetValue(item);
    }
}
Run Code Online (Sandbox Code Playgroud)

使用上述方法,您无需担心设置,ListBox并且它将返回Value项目的预期.它适用于List<T>,Array,ArrayList,DataTable,匿名类型,主要类型的列表,你可以作为数据源使用所有其他列表的列表.以下是一个用法示例:

//Gets underlying value at index 2 based on settings
this.listBox1.GetItemValue(this.listBox1.Items[2]);
Run Code Online (Sandbox Code Playgroud)

由于我们将GetItemValue方法创建为扩展方法,因此当您想要使用该方法时,请不要忘记包含您将该类放入的命名空间.

这种方法适用于ComboBoxCheckedListBox过.


Akr*_*hda 5

如果您正在处理Windows窗体项目,可以尝试以下操作:

将项添加到ListBoxas KeyValuePair对象:

listBox.Items.Add(new KeyValuePair(key, value);
Run Code Online (Sandbox Code Playgroud)

然后,您将能够通过以下方式检索它们:

KeyValuePair keyValuePair = listBox.Items[index];
var value = keyValuePair.Value;
Run Code Online (Sandbox Code Playgroud)


Dav*_*haw 2

这对我有用:

ListBox x = new ListBox();
x.Items.Add(new ListItem("Hello", "1"));
x.Items.Add(new ListItem("Bye", "2"));

Console.Write(x.Items[0].Value);
Run Code Online (Sandbox Code Playgroud)

  • 据我所知,“ListBox.Items”的类型为“System.Windows.Forms.ListBox.ObjectCollection”,这意味着“ListBox.Items[index]”是一个没有 Value 属性的对象! (7认同)