Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# ListBox does not recognize that there is a selection

Tags:

c#

listbox

I'm new to c# so keep that in mind.

I'm building a c# front-end for a restful webservice and I have a listbox which I have put items into:

listBox.DataSource = list;
listBox.DataTextField = "name";
listBox.DataValueField = "id";
listBox.DataBind();

Then I select an item and click a button that activates this code:

long id = Convert.ToInt64(listBox.SelectedItem.Value);

The problem is the SelectedItem is null.

Like I said, I am new to c# so I have no clue what could be wrong.

like image 710
Maroon5Five Avatar asked Mar 27 '26 01:03

Maroon5Five


1 Answers

In your Page_Load event, do this:

if(!IsPostBack)
{
    listBox.DataSource = list;
    listBox.DataTextField = "name";
    listBox.DataValueField = "id";
    listBox.DataBind();
}

Note: This will bind your list box the first time the page is loaded and not on every post back, which is what was wiping out your selected item before. In ASP.NET, click event handlers happen after the Page_Load event happens, so if you do not put a condition on when you bind, then every post back would wipe out the data before your event handler had a chance to find out what the user selected.

like image 144
Karl Anderson Avatar answered Mar 29 '26 14:03

Karl Anderson