DEN
DEN

Reputation: 1893

How to highlight the row column background when same text compare with adjacent rows is found?

I have to highlight the background of the row's column no.3 if same text are found compare with its previous or next row column no.3 text. for example, if 1st row column no.3 and 2nd row column no.3 text are the same, both of its background's cssclass will be "ipsame1". I am able to do it by the posted source code below. However it fails after the gridview is sorted.

protected void gv_useronline_RowDataBound(object sender, GridViewRowEventArgs e)
{
    GridViewRow row = e.Row;

    if (row.RowType == DataControlRowType.DataRow)
    {
        if (compareToPrevious(row.RowIndex, row.Cells[3].Text))
        {
                row.Cells[3].CssClass = "sameIP1";
        }
    }
}

private bool compareToPrevious(int currentRowIndex, string currentRowCellsText)
{
    DataTable dt = Session["useronlineTable"] as DataTable;
    if (currentRowIndex == 0)
    {
        if (currentRowCellsText == dt.Rows[currentRowIndex + 1][3].ToString())
            return true;
    }
    else if (currentRowIndex != dt.Rows.Count - 1)
    {
        if ((currentRowCellsText == dt.Rows[currentRowIndex - 1][3].ToString())|| 
            (currentRowCellsText == dt.Rows[currentRowIndex + 1][3].ToString()))
            return true;
    }
    else
    {
        if (currentRowCellsText == dt.Rows[currentRowIndex - 1][3].ToString())
            return true;
    }

    return false;
}

protected void gv_useronline_Sorting(object sender, GridViewSortEventArgs e)
{

    //Retrieve the table from the session object.
    DataTable dt = Session["useronlineTable"] as DataTable;

    if (dt != null)
    {

        //Sort the data.
        dt.DefaultView.Sort = e.SortExpression + " " + GetSortDirection(e.SortExpression);
        Session["useronlineTable"] = dt;
        gv_useronline.DataSource = dt;


        gv_useronline.DataBind();
    }

}

Upvotes: 1

Views: 181

Answers (1)

jack
jack

Reputation: 1113

I think the issue is in gv_useronline_Sorting method. You can try modifying gv_useronline_Sorting method to be like the following:

protected void gv_useronline_Sorting(object sender, GridViewSortEventArgs e)
{
    //Retrieve the table from the session object.
    DataTable dt = Session["useronlineTable"] as DataTable;

    if (dt != null)
    {
        //Sort the data
        DataView dv = dt.DefaultView;
        dv.Sort = e.SortExpression + " ASC"; // ASC or DESC 
        DataTable dtSorted = dv.ToTable();

        // Put the sorted table in session
        Session["useronlineTable"] = dtSorted;

        // Bind the GridView to the new 
        gv_useronline.DataSource = dt;
        gv_useronline.DataBind();
    }
}

I think it would work like since you have passed the sorted table into session, then in compareToPrevious method it will compare to the sorted table.

Upvotes: 2

Related Questions