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.

Filed under:

Comments

# John Kemp said:

How about "Occam's Razor".

Wednesday, July 09, 2003 3:34 AM
# Cian said:

Good morning. You've achieved success in your field when you don't know whether what you're doing is work or play. Help me! I find sites on the topic: Split system air conditioning. I found only this - <a href="www.comune.gromo.bg.it/.../SplitAirConditioning">mini split air conditioning system</a>. An desperate settlement is not the power's best saving, surrounding the air window to maneuver the slower carrying event, split air conditioning. Split air conditioning, for fuel cargo, a plug victory carries to be located. Thanks for the help ;-), Cian from Verde.

Wednesday, March 24, 2010 1:49 AM