c# - Selected Index Changed Event Firing when it's not supposed to -
i have encountered strange situation asp.net page. form has 2 controls have autopostback="true"
: radiobuttonlist
, dropdownlist
. radiobuttonlist has enableviewstate="false"
. when change selected item of dropdownlist, radiobuttonlist
selectedindexchanged
event fires well. if remove enableviewstate="false"
, behavior goes away. can explain why happening? have included sample code below can see behavior yourself:
<div> <asp:radiobuttonlist id="rbltest" autopostback="true" onselectedindexchanged="rbltest_selectedindexchanged" enableviewstate="false" runat="server"> <asp:listitem text="option 1" value="1" /> <asp:listitem text="option 2" value="2" /> <asp:listitem text="option 3" value="3" /> </asp:radiobuttonlist> <br /> <br /> <asp:dropdownlist id="ddltest" autopostback="true" onselectedindexchanged="ddltest_selectedindexchanged" runat="server"> <asp:listitem text="select one" value="" /> <asp:listitem text="option 1" value="1" /> <asp:listitem text="option 2" value="2" /> <asp:listitem text="option 3" value="3" /> </asp:dropdownlist> <br /> <br /> <asp:button id="btnsubmit" onclick="btnsubmit_click" text="submit" enableviewstate="false" runat="server" /> <br /> <br /> <asp:label id="lblresult" runat="server" /> </div>
here code behind code:
protected void page_load(object sender, eventargs e) { if (!ispostback) { rbltest.selectedindex = 0; } } protected void rbltest_selectedindexchanged(object sender, eventargs e) { lblresult.text += "radiobutton list selectedindexchanged fired<br />"; } protected void btnsubmit_click(object sender, eventargs e) { lblresult.text += "submit button click event fired<br />"; } protected void ddltest_selectedindexchanged(object sender, eventargs e) { lblresult.text += "dropdown list selectedindexchanged event fired<br />"; }
additionally, if comment out line in code behind:
rbltest.selectedindex = 0;
then behavior not occur until select radio button list. appreciated.
when set enableviewstate false, means not gonna keep state of objects. means when autopost, values reset original values.
when post back, changing state of radio button (rbltest.selectedindex = 0) , that's firing event. so, change 1 radio button , 2 events fired.
just else point out, remember every time postback, page recreated @ server-side. , life-cycle of page executed. viewstate used on process populate controls. can read more on: https://msdn.microsoft.com/en-us/library/ms178472%28v=vs.85%29.aspx
Comments
Post a Comment