简体   繁体   中英

Datagridview add row with cell style programmatically

dgvStatus is a DataGridView with one column.

Following line is adding new row

dgvStatus.Rows.Add("XYZ");

But I want to change cell text color so I have written following code

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);

But this code giving error -

在此输入图像描述

How to fix it.

UPDATE:

When I changed my code according to @ASh 's answer

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

Then it is giving following error -

在此输入图像描述

row doesn't have cells until you add it to grid

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

UPDATE

if it doesn't work, try this:

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM