How to avoid RowDataBound while editing a GridView?

I currently have the following code in a RowDataBound:

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.DataRow) { Label groupID = (Label)e.Row.FindControl("idgroup"); LinkButton myLink = (LinkButton)e.Row.FindControl("groupLink"); myLink.Attributes.Add("rel", groupID.Text); } } 

However, when I click the "Edit" link, it tries to run this code and gives an error. Therefore, how can I run this code ONLY when the GridView is in read mode? But not when editing ...

+4
source share
5 answers

Here's how to do it! It will execute code only line by line (when reading or editing), except for the line being edited !!!

 protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.DataRow) { if ((e.Row.RowState == DataControlRowState.Normal) || (e.Row.RowState == DataControlRowState.Alternate)) { Label groupID = (Label)e.Row.FindControl("idgroup"); LinkButton myLink = (LinkButton)e.Row.FindControl("groupLink"); myLink.Attributes.Add("rel", groupID.Text); } } } 
+7
source

you can add validation as follows:

 if (e.Row.RowState != DataControlRowState.Edit) { // Here logic to apply only on initial DataBinding... } 
+6
source

Add validation for e.Row.RowState :

 if ((e.Row.RowState & DataControlRowState.Edit) > 0) { //In Edit mode } 
+2
source

Davide's answer is almost correct. However, it will not work for alternating lines. Here is the correct solution:

 if (e.Row.RowType == DataControlRowType.DataRow && e.Row.RowState != DataControlRowState.Edit && e.Row.RowState != (DataControlRowState.Edit | DataControlRowState.Alternate)) { // Here logic to apply only on rows not in edit mode } 
+2
source

In your gridview, find the OnrowDataBound event, which will look like OnrowDataBound = "GridView1_RowDataBound", delete this code and disable the above code.

0
source

All Articles