Datagridview以编程方式添加具有单元格样式的行

时间:2015-02-26 12:47:37

标签: c# datagridview datagridviewrow datagridviewcellstyle

dgvStatus是一个包含一列的DataGridView。

以下行是添加新行

dgvStatus.Rows.Add("XYZ");

但我想更改单元格文本颜色,所以我写了以下代码

DataGridViewRow row = new DataGridViewRow();
DataGridViewCellStyle style = new DataGridViewCellStyle();
style.ForeColor = Color.Red; // the color change
row.DefaultCellStyle = style;
row.Cells[0].Value = "XYZ";
dgvStatus.Rows.Add(row);

但是这段代码给出了错误 -

enter image description here

如何修复它。

更新:

根据@ASh的答案更改了我的代码

dgvStatus.Rows.Add(row);
row.Cells[0].Value = "XYZ";

然后它给出了以下错误 -

enter image description here

1 个答案:

答案 0 :(得分:0)

行在将其添加到网格

之前没有单元格
dgvStatus.Rows.Add(row);
row.Cells[0].Value = "XYZ";

更新

如果不起作用,请尝试:

int idx = dgvStatus.Rows.Add("test");
var row = dgvStatus.Rows[idx];
DataGridViewCellStyle style = new DataGridViewCellStyle();
style.ForeColor = Color.Red; // the color change
row.DefaultCellStyle = style;
相关问题