9

On my page, I set up a GridView with a few columns. I coded an update, delete and insert method. While my GridView binds its data, the following method is called:

protected void GridViewAutomat_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        if(e.Row.RowState != DataControlRowState.Edit)
        { 
            //some code

        }
    }
}

The Problem with my second if statement is that when my GridView is entering the Edit Mode (when I want to update a record in my GridView) it doesn't catch the RowState Alternate | Edit which looks like this(this is how the RowState is after I call my Update Method):

enter image description here

When I try to combine the two RowStates separately it wont work either:

if(e.Row.RowState != DataControlRowState.Edit && 
   e.Row.RowState != DataControlRowState.Alternate)

The Code in the if-statement should be executed when the row is not in edit (Alternate | Edit) mode, that's why I have != as an operator

Does anyone know how I can catch the combined mode Alternate | Edit and the Edit Mode together?

3 Answers3

4

You can check it in:

  • Edit mode:

    e.Row.RowState != DataControlRowState.Edit
    
  • Alter | Edit mode:

    e.Row.RowState != (DataControlRowState.Edit | DataControlRowState.Alternate)
    

In workaround:

if (e.Row.RowType == DataControlRowType.DataRow &&
    e.Row.RowState != DataControlRowState.Edit && 
    e.Row.RowState != (DataControlRowState.Edit | DataControlRowState.Alternate))
{ 
    //... Here is logic
}

Or:

if (e.Row.RowType == DataControlRowType.DataRow)
{
    if (e.Row.RowState != DataControlRowState.Edit && 
        e.Row.RowState != (DataControlRowState.Edit | DataControlRowState.Alternate))
    {
        //... here is logic
    }
}
3

The RowState value is a DataControlRowState enum, which has the Flags attribute set. This means we can call Enum.HasFlag, like so:

if (e.Row.RowType == DataControlRowType.DataRow &&
    e.Row.RowState.HasFlag(DataControlRowState.Edit))
{ 
    //... Here is logic
}
Ian
  • 1,475
  • 2
  • 15
  • 31
0

The answers already provided already are probably easier to read for human beings who don't use a lot of bitwise operators on a day to day basis. However, an alternative would be to use a binary logical AND &, leveraging that RowState is a bitwise property:

        if (!((e.Row.RowState & DataControlRowState.Edit) > 0))
        { 
            //some code - Executed when RowState is NOT Edit
        }

Note that the example snippet above runs the code block when the row state is NOT in Edit mode in accordance with the original poster's situation. If you need to execute code when the row state IS in Edit mode, simply remove the ! negation, i.e. if (((e.Row.RowState & DataControlRowState.Edit) > 0)).

Credit to one of the responses on this MSDN thread that led me to this solution.

GoldDragonTSU
  • 487
  • 1
  • 9
  • 23