使用绑定数据集中的值设置网格视图行背景颜色

Kri*_*ota 5 c# asp.net datatable gridview

我有一个包含Column的GridView ID

我有一个包含两列的DataTable

ID
DONE
Run Code Online (Sandbox Code Playgroud)

ID将DataTable中的列绑定到GridView.直到没有它的罚款.

但是现在我需要DONE在DataTable中的Column Value 上设置GridView行的背景颜色.(如果DONE值是true行背景颜色必须更改.)

如何在不将DONERow 绑定到GridView的情况下实现此目的?

Nir*_*ngh 7

GridView1_RowDataBound为GridView 创建事件.

if (e.Row.RowType == DataControlRowType.DataRow)
{
    //Check your condition here
    //Get Id from here and based on Id check value in the 
    //underlying dataSource Row where you have "DONE" column value
    // e.g.
    // (gridview.DataSource as DataTable), now you can find your row and cell 
    // of "Done"
    If(Condition True)
    {
        e.Row.BackColor = Drawing.Color.Red;  // your color settings 
    }
}
Run Code Online (Sandbox Code Playgroud)

示例代码段:

protected void EmployeeAvailabilityGridView_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            try
            {
               if (e.Row.RowType == DataControlRowType.DataRow)
                {                  
                    if(Convert.ToBoolean(DataBinder.Eval(e.Row.DataItem, "DONE")))
                    {
                        e.Row.BackColor = System.Drawing.Color.LightPink;
                    }
                }
            }
            catch (Exception ex)
            {
                //ErrorLabel.Text = ex.Message;
            }
        }
Run Code Online (Sandbox Code Playgroud)

有关更详细的实现,请参阅以下链接:
根据条件更改GridView行颜色

注意:如果DataSource中不存在该行,那么您必须具有一些逻辑才能从其他位置获取该行.可能是你ID在另一张表中作为外键.