Get the value for a listbox item by index

155,470

Solution 1

It would be

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

Solution 2

Here I can't see even a single correct answer for this question (in WinForms tag) and it's strange for such frequent question.

Items of a ListBox control may be DataRowView, Complex Objects, Anonymous types, primary types and other types. Underlying value of an item should be calculated base on ValueMember.

ListBox control has a GetItemText which helps you to get the item text regardless of the type of object you added as item. It really needs such GetItemValue method.

GetItemValue Extension Method

We can create GetItemValue Extension Method to get item value which works like 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);
    }
}

Using above method you don't need to worry about settings of ListBox and it will return expected Value for an item. It works with List<T>, Array, ArrayList, DataTable, List of Anonymous Types, list of primary types and all other lists which you can use as data source. Here is an example of usage:

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

Since we created the GetItemValue method as an extension method, when you want to use the method, don't forget to include the namespace which you put the class in.

This method is applicable on ComboBox and CheckedListBox too.

Solution 3

If you are working on a windows forms project you can try the following:

Add items to the ListBox as KeyValuePair objects:

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

Then you will be able to retrieve them the following way:

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

Solution 4

I'm using a BindingSource with a SqlDataReader behind it and none of the above works for me.

Question for Microsoft: Why does this work:

  ? lst.SelectedValue

But this doesn't?

   ? lst.Items[80].Value

I find I have to go back to to the BindingSource object, cast it as a System.Data.Common.DbDataRecord, and then refer to its column name:

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

Now that's just ridiculous.

Solution 5

Suppose you want the value of the first item.

ListBox list = new ListBox();
Console.Write(list.Items[0].Value);
Share:
155,470
tzam
Author by

tzam

Updated on November 29, 2020

Comments

  • tzam
    tzam over 3 years

    This must be very easy but I am stuck. I have a listBox with X Items. Each Item has a text description (Which appears in the listBox) and its value(numerical). I want to be able to get the value property of an item, using the index number of the item.

  • Akram Shahda
    Akram Shahda almost 13 years
    As far as I know, ListBox.Items is of type System.Windows.Forms.ListBox.ObjectCollection which means ListBox.Items[index] is an Object which does not have a Value property !!
  • DaveShaw
    DaveShaw almost 13 years
    This was an answer for WebForms, as he is referring to Settings a Text and Value, that made me assume WebForms, not WinForms.
  • Akram Shahda
    Akram Shahda almost 13 years
    @tzam: I've edited my answer. It will work if you are using the described method ...
  • tzam
    tzam almost 13 years
    The listbox is databound, so it is populated automatically... Do you have any idea how it could work this way? Besides that, your answer works and was great help!!!
  • Akram Shahda
    Akram Shahda almost 13 years
    @tzam: Try to use DictionaryItem instead of KeyValuePair .
  • Mike K
    Mike K over 12 years
    Alternatively I guess I could iterate through the Items collection, selecting each item and then getting SelectedValue. But I shouldn't have to do this, and it's a kludge anyway.
  • Reza Aghaei
    Reza Aghaei almost 8 years
    Items may be DataRowView or a Complex Object or other types. Underlying value of an item should be calculated base on ValueMember.
  • Reza Aghaei
    Reza Aghaei almost 8 years
    An Item in Items collection of a ListBox is of type object and it doesn't have a Value property. The item may be a DataRowView, a complex object or a primary type. The value should be calculated using ValueMember property, the same way SelectedValue works.
  • Reza Aghaei
    Reza Aghaei over 5 years
    In fact at the best case it will return text for an item. Items may be DataRowView or a complex object or other types. The underlying value of an item should be calculated base on ValueMember.