Maroon5Five
Maroon5Five

Reputation: 147

C# ListBox does not recognize that there is a selection

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.

Upvotes: 3

Views: 617

Answers (3)

B H
B H

Reputation: 1878

Even if you have correctly coded to prevent creaming your selections on postback, there is another requirement which must be met in order to avoid the same symptoms. If you supply a DataValueField, the values in that column need to be unique. See the question ASP.NET DropDownList not retaining selected item on postback

Upvotes: 0

Swag
Swag

Reputation: 2140

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

This must be in your Page_Load.

Upvotes: 2

Karl Anderson
Karl Anderson

Reputation: 34846

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.

Upvotes: 4

Related Questions