aleafonso
aleafonso

Reputation: 2256

How to avoid RowDataBound when GridView is edited?

Currently, I have the following code in the 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 on the Edit link, it tries to run that code and throws an error. Therefore, how can I run that code ONLY when the GridView is in read mode? But not when editing...

Upvotes: 4

Views: 13905

Answers (5)

Sameer Alibhai
Sameer Alibhai

Reputation: 3178

Davide's answer is almost correct.. However it will fail for alternate rows. 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
}

Upvotes: 2

aleafonso
aleafonso

Reputation: 2256

Here is how to do it! It will only execute the code over the rows (when reading or editing mode) except for the row that is 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);
            }
        }
    }

Upvotes: 7

Narender
Narender

Reputation: 1

In your gridview, search for OnrowDataBound event which will like OnrowDataBound="GridView1_RowDataBound" remove that code and disable the above code.

Upvotes: 0

Waqas
Waqas

Reputation: 6802

Add a check for e.Row.RowState:

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

Upvotes: 2

Davide Piras
Davide Piras

Reputation: 44605

you can add a check like this:

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

Upvotes: 6

Related Questions