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
- protected void GridView_RowDataBound(object sender, GridViewRowEventArgs e)
- {
- GridView gridView = (GridView)sender;
- if (e.Row.RowType == DataControlRowType.EmptyDataRow || e.Row.RowType == DataControlRowType.Footer || (e.Row.RowState & DataControlRowState.Edit) > 0)
- {
- DropDownList categoryDropDownList = e.Row.FindControl("CategoryDropDownList") as DropDownList;
- this.BindCategoryDropDown(categoryDropDownList);
- if (e.Row.RowState == DataControlRowState.Edit)
- {
- var teamUpdate = e.Row.DataItem as TeamUpdate;
- if (categoryDropDownList != null && teamUpdate != null)
- {
- categoryDropDownList.Items.FindByText(teamUpdate.Category).Selected = true;
- }
- }
- }
- /// <summary>
- /// Binds the category drop down.
- /// </summary>
- /// <param name="dropDownList">The drop down list.</param>
- private void BindCategoryDropDown(DropDownList dropDownList)
- {
- if (dropDownList == null)
- {
- return;
- }
- dropDownList.DataSource = this.ReportCategories;
- dropDownList.DataValueField = "Key";
- dropDownList.DataTextField = "Value";
- dropDownList.DataBind();
- }
So,in short, use:
(e.Row.RowState & DataControlRowState.Edit) > 0)
not
e.Row.RowState == DataControlRowState.Edit
Cheers ![]()




