【发布时间】:2017-06-15 01:19:03
【问题描述】:
我正在尝试根据其中一列中的文本更改 datagridviewer 中行的颜色。我收到错误消息:对象引用未设置为第一个 if 语句行上的对象实例。我根据数据源填写了datagridviewer,代码也在下面。
void ChangeDataGridViewColor()
{
foreach (DataGridViewRow Row in datagridviewTreatmentPrep.Rows)
{
if (Row.Cells["Primary Onc"].Value.ToString() == "JMK")
{
Row.DefaultCellStyle.BackColor = Color.Green;
}
if (Row.Cells["Primary Onc"].Value.ToString() == "DBF")
{
Row.DefaultCellStyle.BackColor = Color.Orange;
}
else
{
Row.DefaultCellStyle.BackColor = Color.White;
}
}
}
void FillDataGridViewTreatmentPrep()
{
string constring = "datasource = RadOncViewerDatabase.db";
string TreatPrepQuery = "SELECT * FROM TreatmentPrep";
SQLiteConnection connectionstring = new SQLiteConnection(constring);
connectionstring.Open();
DataTable dsTreatPrep = new DataTable();
SQLiteDataAdapter adapterTreatPrep = new SQLiteDataAdapter(TreatPrepQuery, constring);
adapterTreatPrep.Fill(dsTreatPrep);
datagridviewTreatmentPrep.DataSource = dsTreatPrep;
//datagridviewTreatmentPrep.BindingContext = new BindingContext();
//this.datagridviewTreatmentPrep.DataSource = dsTreatPrep.Tables[0].DefaultView.ToTable(true, "Patient_Name");
}
【问题讨论】:
-
您确定
Row.Cells["Primary Onc"].Value不为空吗?您知道该行存在...但它的值可能不存在。 -
是的。列名称的值为 Primary Onc。我认为混淆可能在于我已经用数据集填充了 datagridviewer 并且我没有正确引用该列。
-
单步执行代码并查看
dsTreatPrep中的列名,如果没有名为Primary Onc的列,那么这将解释您的错误。 -
此外,由于
DataGridView已绑定到表,因此您需要使用Row.DataBoundItem之类的内容从数据表中获取正确的值。 -
可能需要在
DataBindingComplete事件中/之后调用,或者在RowPrePaint事件中更好地调用stackoverflow.com/questions/2189376/…
标签: c# datagridview