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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With