How can I get the previous row in gridview rowdata

2019-08-28 23:07发布

问题:

I would like to check the previous row data if it is equal to --, if it is not equal to -- then I would enable button in the next row

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
       if (DataBinder.Eval(e.Row.DataItem, "time_start").ToString() == "--")
       {
            Button btn = ((Button)e.Row.FindControl("Edit_Button"));
            btn.Enabled = false;
       }   
    }
}

回答1:

You can also do it like this using GridView1.Rows[e.Row.RowIndex - 1].

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        GridViewRow prevrow = GridView1.Rows[e.Row.RowIndex - 1];
        if( prevrow.RowType == DataControlRowType.DataRow)
        {
            // Your code for manipulating prevrow
        }
        if (DataBinder.Eval(e.Row.DataItem, "time_start").ToString() == "--")
        {
            Button btn = ((Button)e.Row.FindControl("Edit_Button"));
            btn.Enabled = false;
        }
    }
}


回答2:

One way to do this is:

  • Create a field previousRow in your class, of type GridViewRow.

  • Initialize this field to null in the a GridView.DataBinding event handler. This event is fired when databinding starts, before any of the RowDataBound events fires.

  • In your GridView.RowDataBound event handler, do your processing (including comparing with previousRow), then set previousRow = e.Row.