Question

In Windows Forms 4.5 I'm using a simple ListBox and adding items dynamically in code-behind like this:

for (int i = 0; i < rawshows.Count; i++)
{
    var item = rawshows[i];
    if (/* some comparisons I will not bore you with */)
    {
        ListItem li = new ListItem(item.ShowName, i.ToString());
        shows.Add(li);
    }
}
lbShows.DataSource = shows;
lbShows.DataBind();

As you can see, the text of the element is set to the item.ShowName (which is a string) and the value is set to the value of the i counter.

Everything seems fine, the list gets populated correctly. The problem is when I retrieve the selected item from the list. This:

lbShows.SelectedItem.Value

evaluates to the same value as

lbShows.SelectedItem.Text

(where lbShows is the listBox). Basically they both evaluate to the show name, instead of the number I set when populating the list.

Any clues on what I'm doing wrong?

Was it helpful?

Solution

Specify the DataTextField and the DataValueField" before calling .DataBind()

        lbShows.DataTextField = "TextColumnName";
        lbShows.DataValueField = "ValueColumnName";
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top