michalstanko
michalstanko

Reputation: 589

DropDownList.SelectedItem sometimes null, sometimes not after postback, EnableViewState=False

I have two very similar .aspx pages. Both of them contain a DropDownList control. Both DropDownList controls' EnableViewState is set to False:

<asp:DropDownList ID="ddl" runat="server" EnableViewState="False" />

There is a LinkButton on both pages. In the btn_Click handler, if I try to access ddl.SelectedItem property (which, as far as I know, should be null because of the EnableViewState=False, am I correct?), it is null on one page, but not null (it has a correct value) on the other page. Can you give me any pointers how can that be possible?

string txt = ddl.SelectedItem.Text; // SelectedItem sometimes null, other times not

The difference between those two pages's dropdowns is, that in one case, the dropdown is filled using AjaxToolkit's CascadingDropDown control (in that case, SelectedItem is not null, despite having EnableViewState property set to false), in the other case, dropdown's items are being filled in the Page_Load property, within and if-block, checking whether IsPostBack is false (items are only filled on the first request, I won't need them after the postback).

Thank you.

Upvotes: 0

Views: 1564

Answers (3)

Brian Mains
Brian Mains

Reputation: 50728

Looks like the selected index gets posted back to the server when you change the value; the selected index property gets applied once items are applied in the list, so if you have no items, I don't believe it gets applied until some items get added to the list. So, if you bind the list again, and a value got selected from the list, and you rebind the drop down, it would apply the selected index. That could be it possibly.

HTH

Upvotes: 0

Stephen M. Redd
Stephen M. Redd

Reputation: 5428

CascadingDropDown doesn't honor the enable viewstate setting. If you need it null, you should reset it to null on page load or a similar event.

Upvotes: 1

Jeremy McGee
Jeremy McGee

Reputation: 25210

If you have something populating the drop-down through JavaScript then ASP.NET will see that value, irrespective of how it got there.

Upvotes: 0

Related Questions