我正在尝试根据其中一列中的文本更改datagridviewer中行的颜色。我收到错误:对象引用未设置为第一个if语句行上的对象实例。我根据数据源填写了datagridviewer,代码也在下面。
[default]
Exten => 101,1,Answer
Exten => 101,n,NoOp(Test101)
Exten => 101,n,Dial(SIP/101,12,r)
Exten => 101,n,VoiceMail(101@interno-ipca)
Exten => 101,n,Hangup()
Exten => 102,1,Answer
Exten => 102,n,NoOp(Test102)
Exten => 102,n,Dial(SIP/102,12,r)
Exten => 102,n,VoiceMail(102@interno-ipca)
Exten => 102,n,Hangup()
答案 0 :(得分:2)
使用RowPrePaint
事件,不要对可能为null的对象使用.ToString()
:
private void dataGridView1_RowPrePaint(object sender, DataGridViewRowPrePaintEventArgs e)
{
if (e.RowIndex < 0) return;
var row = (sender as DataGridView).Rows[e.RowIndex];
string value = Convert.ToString(row.Cells["Primary Onc"].Value);
//or in VS 2015: string value = row.Cells["Primary Onc"].Value?.ToString();
if (value == "JMK")
row.DefaultCellStyle.BackColor = Color.Green;
else if (value == "DBF")
row.DefaultCellStyle.BackColor = Color.Orange;
else
row.DefaultCellStyle.BackColor = Color.White;
}
答案 1 :(得分:1)
以下是我测试的代码,它按预期工作。抱歉延误。
foreach (DataGridViewRow Row in dataGridView1.Rows) {
DataRowView drv = (DataRowView)Row.DataBoundItem;
if (drv != null) {
if (drv.Row["Primary Onc"].ToString() == "JMK") {
Row.DefaultCellStyle.BackColor = Color.Green;
}
else {
if (drv.Row["Primary Onc"].ToString() == "DBF") {
Row.DefaultCellStyle.BackColor = Color.Orange;
}
else {
Row.DefaultCellStyle.BackColor = Color.White;
}
}
}
}
希望这有帮助。
答案 2 :(得分:0)
您必须使用DataGridViewCellStyle类 我的解决方案:
int max = dgv.Rows.Count;
DataGridViewCellStyle style;
for (int i = 0; i < max; i++)
for (int j = 2; j < dgv.Columns.Count; j++)
if (dgv[j, i].Value.ToString() == "")
{
style = dgv[j, i].Style;
style.BackColor = Color.Red;
dgv[j, i].Style = style;
}