Reputation: 3575
I have datagridview and now I would like to change background color of its each row depending whether row number is even or odd.
I thought that there must be easier way to reach that. Then using for example this part of code and modify it so it would change the colours of dtg's row. If this snippet of code is one of the ways to do that, may someone help me to improve it so it wouldn't throw exception when index is out if rabge?
public void bg_dtg()
{
try
{
for (int i = 0; i <= dataGridView1.Rows.Count ; i++)
{
if (IsOdd(i))
{
dataGridView1.Rows[i].DefaultCellStyle.BackColor = Color.LightBlue;
}
}
}
catch (Exception ex)
{
MessageBox.Show(""+ex);
}
}
public static bool IsOdd(int value)
{
return value % 2 != 0;
}
Thank you for your time and answers.
Upvotes: 17
Views: 37151
Reputation: 148150
You are getting exception because you are accessing row that is not present. GridView rows are zero based index
, it means if you have ten rows in grid the index will be from 0 to 9 and you should iterate one less then the rows count
. The i <= dataGridView1.Rows.Count
will give exception on last iteration because when count is 10 (total rows are ten) and dataGridView1.Rows[10] does not exists therefore exception is thrown.
Change <= in loop condition to <
for (int i = 0; i <= dataGridView1.Rows.Count ; i++)
To
for (int i = 0; i < dataGridView1.Rows.Count ; i++)
You Should AlternatingRowsDefaultCellStyle property to set alternative row style to keep it simple and efficient.
Upvotes: 6
Reputation: 41
AlternatingRowStyle-BackColor = "#C5C5C5"
We can directly add the code in the ASP grid
<asp:GridView ID="Gridview1" runat="server"
AlternatingRowStyle-BackColor = "#F3F3F3"
AutoGenerateColumns="true">
</asp:GridView>
Upvotes: 4
Reputation: 79
you can try this code
for (int i = 0; i < GridView1.Rows.Count; i++) {
if (i % 2 == 0) {
GridView1.Rows[i].Cells[0].Style.BackColor = System.Drawing.Color.Green;
GridView1.Rows[i].Cells[1].Style.BackColor = System.Drawing.Color.Green;
}
else {
GridView1.Rows[i].Cells[0].Style.BackColor = System.Drawing.Color.Red;
GridView1.Rows[i].Cells[1].Style.BackColor = System.Drawing.Color.Red;
}
}
Upvotes: 5
Reputation: 10246
You can use AlternatingRowsDefaultCellStyle
OR
you can also do it manually
foreach (DataGridViewRow row in dataGridView1.Rows)
if (row.Index % 2==0 )
{
row.DefaultCellStyle.BackColor = Color.Red;
}
Upvotes: 4
Reputation: 1055
There is a DataGridView
alternate row view style option in the forms designer. AlternatingRowsDefaultCellStyle
in the properties grid
Upvotes: 32