简体   繁体   中英

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!!

// 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);
}

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 .

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";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM