我的目标是将样式应用于状态等于Rejected
的行。问题是,我的代码没有应用样式。
代码
public void RefreshGrid()
{
// MySQL connection string
using (var conn = new MySqlConnection(ConnectionString.ConnString))
{
using (var mySqlDataAdapter = new MySqlDataAdapter("select id, name, status from table", conn))
{
using (var dataSet = new DataSet())
{
DataSet DS = new DataSet();
mySqlDataAdapter.Fill(DS);
dataGrid.DataSource = DS.Tables[0];
dataGrid.Columns[0].HeaderText = "ID";
dataGrid.Columns[1].HeaderText = "Name";
dataGrid.Columns[2].HeaderText = "Status";
// Set visibility to none
dataGrid.Columns[0].Visible = false;
}
}
}
// Where status = Rejected format cell style to Red
foreach (DataGridViewRow Myrow in dataGrid.Rows)
{
MessageBox.Show(Myrow.Cells[2].Value.ToString()); // This shows me `Rejected` and some `Verified`
if (Myrow.Cells[2].Value.ToString() == "Rejected")
{
Myrow.DefaultCellStyle.BackColor = Color.Red;
}
else
{
Myrow.DefaultCellStyle.BackColor = Color.White;
}
}
}
摘要
我很困惑为什么它不涂红色?我以前使用过这个代码,工作得很好。
甚至用MessageBox.Show()
来确认某些行包含Rejected
的值。
我哪里错了?
编辑1
将else语句设置为红色,类似于
foreach (DataGridViewRow Myrow in documentRequestsHistory.Rows)
{
if (Myrow.Cells[12].Value.ToString() == "Rejected")
{
Myrow.DefaultCellStyle.BackColor = Color.Red;
}
else
{
Myrow.DefaultCellStyle.BackColor = Color.Red;
}
}
不应用任何样式。
红色不适用于代码,因为DataGridView还没有办法检查有问题的列的值并相应地设置所需的单元格样式。实际上,foreach
块只是切换整个列的BackColor
属性。
要使其工作,请处理CellFormatting
事件以检查目标列的值,然后设置所需的样式:
private void dataGrid_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
if (e.ColumnIndex == 2)
e.CellStyle.BackColor = e.Value?.ToString().ToLower() == "rejected"
? Color.Red
: Color.White;
}
切换行的BackColor
:
private void dataGrid_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
if (e.ColumnIndex == 2)
((DataGridView)sender)
.Rows[e.RowIndex]
.DefaultCellStyle
.BackColor = e.Value?.ToString().ToLower() == "rejected"
? Color.Red
: Color.White;
}
在设置为红色之前或之后,是否尝试应用UseBackColor=true?