marai
marai

Reputation: 875

Extracting selected value from a ListBox

how do i extract out the selected text and values from a list box. Here's how I populate the list box

           // Populate ListBox

            ListItem lstListItem = new ListItem();

            int intRecordCount = objDataSet.Tables[0].Rows.Count;

            for (int i = 0; i <= intRecordCount - 1; i++)
            {
                lstListItem.Text = objDataSet.Tables[0].Rows[i]["SN_Notes"];
                lstListItem.Value = objDataSet.Tables[0].Rows[i]["ID"];
                this.lstNote.Items.Add(lstListItem);
            }

then when i try to fetch the selected values, It return null value. I'm using Winform / VS2010

           intRecordCount = lstNote.Items.Count;

           for (int i = 0; i <= intRecordCount - 1; i++)
           {
                  lstNote.SelectedIndex = i;
                  strID = lstNote.SelectedValue.ToString(); // Always return Null Value
           }

Thank you in advance!!

Upvotes: 0

Views: 2362

Answers (3)

Peter Pedal
Peter Pedal

Reputation: 21

// Populate ListBox
int intRecordCount = objDataSet.Tables[0].Rows.Count;

for (int i = 0; i <= intRecordCount - 1; i++)
{
    ListItem lstListItem = new ListItem();
    lstListItem.Text = objDataSet.Tables[0].Rows[i]["SN_Notes"];
    lstListItem.Value = objDataSet.Tables[0].Rows[i]["ID"];
    this.lstNote.Items.Add(lstListItem);
}

Upvotes: 2

ionden
ionden

Reputation: 12776

First, you don't bind correctly the ListBox. You should try using this code:

lstListItem.DataSource = objDataSet.Tables[0];
lstListItem.DisplayMember = "SN_Notes";
lstListItem.ValueMember = "ID";

Upvotes: 0

Shai
Shai

Reputation: 25619

Your code is baaad :|

    // Populate ListBox
    int intRecordCount = objDataSet.Tables[0].Rows.Count;

    for (int i = 0; i <= intRecordCount - 1; i++)
    {
        ListItem lstListItem = new ListItem();
        lstListItem.Text = objDataSet.Tables[0].Rows[i]["SN_Notes"];
        lstListItem.Value = objDataSet.Tables[0].Rows[i]["ID"];
        this.lstNote.Items.Add(lstListItem);
    }

You need to create a new instance of ListItem on each iteration - otherwise, your ListBox will contain multiple copies of a single ListItem.

Upvotes: 1

Related Questions