如何在找到相同文本与相邻行比较时突出显示行列背景?

时间:2014-03-05 12:02:49

标签: c# asp.net gridview

如果发现相同的文本与其上一行或下一行第3列文本相比,我必须突出显示行第3列的背景。 例如,如果第1行第3列和第2行第3列文本相同,则其背景的cssclass都将为“ipsame1”。我可以通过下面发布的源代码来完成它。但是,在对gridview进行排序后它会失败。

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();
    }

}

1 个答案:

答案 0 :(得分:2)

我认为问题出在gv_useronline_Sorting方法中。您可以尝试将gv_useronline_Sorting方法修改为如下所示:

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();
    }
}

我认为它会起作用,因为你已经将已排序的表传递给会话,然后在compareToPrevious方法中它将与已排序的表进行比较。