首页 文章

按索引获取列表框项的值

提问于
浏览
13

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

7 回答

  • 12

    这将是

    String MyStr = ListBox.items[5].ToString();
    
  • 1

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

    ListBox 控件的项目可以是 DataRowView ,复杂对象,匿名类型,主要类型和其他类型 . 项目的基础 Value 应根据 ValueMember 计算 .

    ListBox control具有 GetItemText ,无论您添加为项目的对象类型如何,它都可以帮助您获取项目文本 . 它真的需要这样的方法 .

    GetItemValue Extension Method

    我们可以创建 GetItemValue extension method来获取类似于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);
        }
    }
    

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

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

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

    此方法也适用于 ComboBoxCheckedListBox .

  • 6

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

    将项目添加到 ListBox 作为 KeyValuePair 对象:

    listBox.Items.Add(new KeyValuePair(key, value);
    

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

    KeyValuePair keyValuePair = listBox.Items[index];
    var value = keyValuePair.Value;
    
  • 1

    我正在使用一个带有SqlDataReader的BindingSource,并且以上都不适用于我 .

    微软的问题:为什么这样做:

    ? lst.SelectedValue
    

    但这不是吗?

    ? lst.Items[80].Value
    

    我发现我必须回到BindingSource对象,将其转换为System.Data.Common.DbDataRecord,然后引用它的列名:

    ? ((System.Data.Common.DbDataRecord)_bsBlocks[80])["BlockKey"]
    

    现在那太荒谬了 .

  • 4

    假设您想要第一个项目的值 .

    ListBox list = new ListBox();
    Console.Write(list.Items[0].Value);
    
  • 5

    这对我有用:

    ListBox x = new ListBox();
    x.Items.Add(new ListItem("Hello", "1"));
    x.Items.Add(new ListItem("Bye", "2"));
    
    Console.Write(x.Items[0].Value);
    
  • 2

    只需尝试这个listBox就是你的列表,yu是一个可靠的索引0的值将被分配

    string yu = listBox1.Items[0].ToString();
    MessageBox.Show(yu);
    

相关问题