0

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 -

enter image description here

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 -

enter image description here

MD SHAHIDUL ISLAM
  • 14,325
  • 6
  • 82
  • 89

1 Answers1

0

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;
ASh
  • 34,632
  • 9
  • 60
  • 82