Wednesday, May 17, 2006

FixListControl - select correct item on PostBack for CheckBoxList/DropDownList/ListBox/RadioButtonList (ASP.NET)

When you add a DropDownList (or any other web controls that inherit from ListControl) to a page and bind it on page load, the first value ends up being selected (or to be more accurate, no value gets selected, so by default the first item is shown) on PostBack (rather than the one you selected). One solution to this is to check if a PostBack has occured and only set up the DropDownList on initial page load.

private void Page_Load(object sender, EventArgs e)
{
 if(!IsPostBack)
 {
  SetupMyDropDown();
 }
}

This helps in most cases, but not if you do a DataBind for the whole page.

private void Page_Load(object sender, EventArgs e)
{
 if(!IsPostBack)
 {
  SetupMyDropDown();
 }
 BindData();
}

This could cause a "Object reference not set to an instance of an object" error, because your DropDownList is bound to an object that needs to be set up on each page load (it is not persisted in view state). One solution would be to bind everything but the DropDownList, but that would not be viable if you needed to bind the whole page (e.g. in your HTML you had <title><%# PageTitle %></title>.

Another solution would be to change the selected value before the page renders. The following method does this (and only if the user is posting back).

private void InitializeComponent()
{
 this.Load += new EventHandler(this.Page_Load);
 this.MyDropDown.PreRender += new EventHandler(this.FixListControl);
}
private void FixListControl(object sender, EventArgs e)
{
 if(IsPostBack)
 {
  ListControl l = (ListControl)sender;
  l.SelectedValue = Request.Form[l.ClientID];
 }
}

Very little code is needed and you can use it for anything that inherits from ListControl, so the following should work as well (I have only tested it with DropDownList):

this.MyCheckBoxList.PreRender += new EventHandler(this.FixListControl);
this.MyDropDown.PreRender += new EventHandler(this.FixListControl);
this.MyListBox.PreRender += new EventHandler(this.FixListControl);
this.MyRadioButtonList.PreRender += new EventHandler(this.FixListControl);

Tags: , , , , , , ,

No comments: