Archive for April, 2013

Loading a Dropdown in Gridview Edit Mode

Posted: 16th April 2013 in ASP.NET
Tags:

I’ve just came across and strange phenomenon when using a grid view control. The scenario I encountered occurred when the edit event was fired

Scenario:

To allow items to be added to the grid view I added a text box and a dropdown to the footer which works fine.

However, if, at a future date, I needed to edit the added item I need to load the dropdown into the row being edited and set the previously selected item.  In principal this seemed fairly straight forward by just checking the RowState on the RowDataBound event to see if it was in edit mode (DataControlRowState.Edit).  In practice this only worked on every second/alternate row. 

It turns out you have to use a bitwise comparison to get it to work as seen in the Row Data Bound code below

Row Data Bound
  1. protected void GridView_RowDataBound(object sender, GridViewRowEventArgs e)
  2.         {
  3.             GridView gridView = (GridView)sender;
  4.             if (e.Row.RowType == DataControlRowType.EmptyDataRow || e.Row.RowType == DataControlRowType.Footer || (e.Row.RowState & DataControlRowState.Edit) > 0)
  5.             {
  6.                 DropDownList categoryDropDownList = e.Row.FindControl("CategoryDropDownList") as DropDownList;
  7.                 this.BindCategoryDropDown(categoryDropDownList);
  8.                 if (e.Row.RowState == DataControlRowState.Edit)
  9.                 {
  10.                     var teamUpdate = e.Row.DataItem as TeamUpdate;
  11.                     if (categoryDropDownList != null && teamUpdate != null)
  12.                     {
  13.                             categoryDropDownList.Items.FindByText(teamUpdate.Category).Selected = true;
  14.                     }
  15.                 }
  16.             }

Bind Dropdown
  1. /// <summary>
  2.       /// Binds the category drop down.
  3.       /// </summary>
  4.       /// <param name="dropDownList">The drop down list.</param>
  5.       private void BindCategoryDropDown(DropDownList dropDownList)
  6.       {
  7.           if (dropDownList == null)
  8.           {
  9.               return;
  10.           }
  11.  
  12.           dropDownList.DataSource = this.ReportCategories;
  13.           dropDownList.DataValueField = "Key";
  14.           dropDownList.DataTextField = "Value";
  15.           dropDownList.DataBind();
  16.       }

 

So,in short, use:

(e.Row.RowState & DataControlRowState.Edit) > 0)

not

e.Row.RowState == DataControlRowState.Edit

Cheers Smile