簡體   English   中英

更改不同值的單元格顏色 - Gridview

[英]Change cell color on different values - Gridview

我需要區分兩個連續的細胞。

連續的每一個,如果它們具有不同的值,則在數據綁定時將值指向gridview。

因此,如果在行1中我有單元格“ABC”而在行2中我有單元格“CBA”。

我需要用不同的顏色為每個單元格着色。

最好的方法是什么?

這稱為條件格式

您可以在標記中啟用RowDataBound事件

<asp:GridView ID="gridview1" runat="server" OnRowDataBound="RowDataBound">

</asp:GridView>

並將其放在Code-Behind文件中。

protected void RowDataBound(Object sender, GridViewRowEventArgs e)
{
    if(e.Row.RowType == DataControlRowType.DataRow)
    {
        if(e.Row.RowIndex == 0)     // This is row no.1
            if(e.Row.Cells[0].Text == "ABC")
                e.Row.Cells[0].BackColor = Color.Red;

        if(e.Row.RowIndex == 1)     // This is row no.2
            if(e.Row.Cells[0].Text == "CBA")
                e.Row.Cells[0].BackColor = Color.Green;
    }
}

在頁面的html部分添加到gridview OnRowDataBound =“gridView1_DataBinding”。 然后添加事件處理程序codebehind:

protected void gridView1_DataBinding(object sender, GridViewRowEventArgs e)
    {

        if (e.Row.RowType != DataControlRowType.DataRow) return;

        var c = e.Row.FindControl("IdOfControl") as Label;
        if(c != null)
        {
            if (c.Text == "ABC")
                e.Row.BackColor = GetColor("Gray");

            if (c.Text == "BCA")
                e.Row.BackColor = GetColor("Green");
        }
    }

    private Color GetColor(string color)
    {
        return Color.FromName(color);
    }

最好的問候,迪馬。

如果我理解你的話,你想要改變一個單元格的顏色,這取決於它的價值。 如果這是正確的,你可以嘗試這樣:

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        if ((Label)e.Row.Cells[0].FindControl("ValueHoldingControl").Text == "ABC")
        {
            //Coloring the cell
        }
    }
}

你可以在gridview的rowdatabound事件上做到這一點。 將上一行保留在viewstate或session中,並將其與下一行匹配。 如果不匹配,請更改顏色,否則不要更改。

void gvShowFullDetail_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            e.Row.BackColor = System.Drawing.ColorTranslator.FromHtml("#AECD6F");
        }
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM