我有一個DataGridView顯示一個DataTable的內容。如何根據單元格的值更改DataGridView中行的背景顏色?
我想根據此行中單元格的值設置行的背景顏色。
請注意有問題的單元格在DataGridView(Visible = False)中未顯示的列中。
我有一個DataGridView顯示一個DataTable的內容。如何根據單元格的值更改DataGridView中行的背景顏色?
我想根據此行中單元格的值設置行的背景顏色。
請注意有問題的單元格在DataGridView(Visible = False)中未顯示的列中。
如果處理RowDataBound事件,則可以檢查數據的值並修改單元格的屬性或在該事件處理程序中應用不同的樣式。
protected void Page_Load(object sender, EventArgs e)
{
GridView g1 = new GridView();
g1.RowDataBound += new GridViewRowEventHandler(g1_RowDataBound);
}
void g1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.DataRow)
{
// Check the Value
if(e.Row.Cells[1].Text = someValue)
{
e.Row.Cells[1].CssClass = "colorCellRed";
}
}
}
這應該會給你你想要的。讓我知道如果你需要它在VB而不是C#。
祝你好運!如已經提到的,RowDataBound;
RowDataBound,你也可以檢查你的數據對象的值,以及文本中網格本身:
void gridView_DataBound(object sender, GridViewEventArgs e) { if (e.Row.RowType == DataControlRowType.DataRow) { var myObject = (myObject)e.DataItem; if (myObject.IsOverdue()) { e.Row.CssClass = "overdue"; } } }
另一種選擇是使用CellFormatting事件。 第一個選項顯示訪問綁定的數據項,並且如果您沒有爲有問題的數據設置列,這會很有用。如果列中有可見或不可見,則第二個選項有效。
private void dataGridView_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
if (((MyDataObject)dataGridView.Rows[e.RowIndex].DataBoundItem).Condition == Value)
{
e.CellStyle.BackColor = System.Drawing.Color.Gold;
}
}
//辦法二 - 可以用它代替的ColumnName
ColumnIndexprivate void dataGridView_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
if (dataGridView["ColumnName", e.RowIndex].Value).Condition == TargetValue)
{
e.CellStyle.BackColor = System.Drawing.Color.Gold;
}
}