Remove Gridview row in rowDataBound event asp.net c#

sajanyamaha picture sajanyamaha · Dec 21, 2012 · Viewed 12.3k times · Source

I have a gridview which checks some values on rowDataBound event.I want to remove some rows based on conditions checked in rowDataBound.I tried putting all controls in a Panel and hiding that panel ie,

TRY 1 :

protected void grdFeatured_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        //some other codes here
        //IMPLEMENT FILTER ACCORDING TO ABOVE 'VIS' OUTPUT
        if (vis > 0)
        {
            Panel1.Visible = false;
        }
    }
}

PROBLEM :

This messes up the paging since rows are hidden but page count occurs and shows page numbers for the remaining visible rows.

TRY 2 :

protected void grdFeatured_RowDataBound(object sender, GridViewRowEventArgs e)
{
    GridViewRow gvr = e.Row;
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        //some other codes here
        //IMPLEMENT FILTER ACCORDING TO ABOVE 'VIS' OUTPUT
        if (vis > 0)
        {
            gvr.Parent.Controls.RemoveAt(gvr.RowIndex);
        }
    }
}

PROBLEM :

gives error :

Specified argument was out of the range of valid values.
Parameter name: index at gvr.Parent.Controls.RemoveAt(gvr.RowIndex);

dont want to edit datasource, help me out guys .

Answer

LNRao picture LNRao · Dec 21, 2012
if (e.Row.RowType == DataControlRowType.DataRow)
        {
            if (somecondition)
            {
                e.Row.Visible = false;
            }
        }