【发布时间】:2017-02-05 04:59:32
【问题描述】:
我有一个如下的datagridview:
我想要:
表单加载时,如果
Gender列的值为Male,则Name列对应的颜色单元格为白色如果更改
Gender列的值:男性→女性,Name列的颜色单元格将为深灰色, 否则如果更改Gender列的值:女性→男性,Name列的颜色单元格将为白色
我试过了,但我做不到:
private void dataGridView_CurrentCellDirtyStateChanged(object sender, EventArgs e)
{
DataGridView dgv = sender as DataGridView;
DataGridViewCell cell = dgv.CurrentCell;
if (dgv.Rows[cell.RowIndex].Cells["Gender"].Value.ToString().Trim() == "Male")
{
// Male
dgv.Rows[cell.RowIndex].DefaultCellStyle.BackColor = Color.White;
}
else
{
// Female
dgv.Rows[cell.RowIndex].DefaultCellStyle.BackColor = Color.DarkGray;
}
}
或者:
private void dataGridView_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
DataGridView dgv = sender as DataGridView;
if (dgv.Columns[e.ColumnIndex].Name.Equals("Gender"))
{
if (e.Value != null && e.Value.ToString().Trim() == "Male")
{
e.CellStyle.BackColor = Color.White;
}
else
{
e.CellStyle.BackColor = Color.DarkGray;
}
}
//if (dgv.Rows[e.RowIndex].Cells["Gender"].Value.ToString().Trim() == "Male")
//{
// e.CellStyle.BackColor = Color.White;
//}
//else
//{
// e.CellStyle.BackColor = Color.DarkGray;
//}
}
任何关于这些的提示都会有很大帮助。提前致谢。
【问题讨论】:
-
看看CellFormatting event。那里的例子可以帮助你做你想做的事
-
This 可能会有所帮助。
-
感谢您的回复。我不用
DataTable那个用DataGridViewRow来显示数据,那怎么办?对不起,我是 C# 新手 -
@MinhKiyo 关注单元格格式化事件。
-
伯凯:我用
dataGridView_CellFormatting更新了我的问题,但它不能