Reputation: 61
I want to set the background color for specified Row in datagridview ..
My need is i have a for loop (i=0;i<10;i++)
.Inside this for loop i write the logic
as
if(i=1)
{
//Want to Set Color For This Specified Row..
dataGridView1.SelectedRows[1].DefaultCellStyle.SelectionBackColor = Color.Yellow;
}
if(i=1)
{
//Want to Set Color For This Specified Row..
dataGridView1.SelectedRows[2].DefaultCellStyle.SelectionBackColor = Color.Blue;
}
if(i=1)
{
//Want to Set Color For This Specified Row..
dataGridView1.SelectedRows[3].DefaultCellStyle.SelectionBackColor = Color.Red;
}
But i didn't get the expected o/p . I hope U understand My need . Please Help Me.
Upvotes: 2
Views: 5487
Reputation: 11844
Instead of using SelectedRows
property of the DataGridview you can use as follows
dataGridView1.Rows[1].DefaultCellStyle.ForeColor = Color.Red;
Because SelectedRows
property will return rows when row(s) has been selected by the User only, if no rows are selected then your code will throw exception.
EDIT :
For your doubt here am providing a sample code, hope it will help you.
for (int i = 0; i < 10; i++)
{
if (dataGridView1.Rows.Count > i)
{
if (i == 1)
dataGridView1.Rows[i].DefaultCellStyle.ForeColor = Color.Red;
else if (i == 2)
dataGridView1.Rows[i].DefaultCellStyle.ForeColor = Color.Blue;
else
dataGridView1.Rows[i].DefaultCellStyle.ForeColor = Color.Green;
}
}
Upvotes: 2
Reputation: 5083
You may handle different events of your datagrid and set cell style
Here is example from related question
private void dgvStatus_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
if (e.ColumnIndex != color.Index)
return;
e.CellStyle.BackColor = Color.Red;
}
Upvotes: 1