ListBox Selection is null / -1 on PostBack

Sometimes stupid errors take up the most time because you get used to handle complex problems.

This little problem has struck me several times, and I always forget what I do wrong so this time it became a blogentry.

When using the System.Web.UI.WebControls.DropDownList or System.Web.UI.WebControls.ListBox from time to time the SelectedItem property returns null and SelectedIndex returns -1 no matter how hard I select an item in the list or combobox.

After having placed breakpoints all around and switched on and of ViewState and PostBack properties I finally got it (again).

Don't refill or DataBind() the list control when Page.IsPostBack (stupid). It's just too many things that may seem natural to check before this.

The simplest solution is always the best. (BTW: this saying is quoted in the movie Contact by Matthew McConaughey as "Somethings law". does anyone remember whos law it was?)

So I encapsulated the fill method with if(!Page.IsPostBack) and it was all good.

1 Comment

Comments have been disabled for this content.