两种方法
第一种
DataGridview1.Rows[i].DefultCellStyle.backcolor
第二种
AlternatingRowsDefutCellstyle 属性
获取或设置应用于DataGridview的奇数行的默认单元格样式。
RowsDefultCellStyle 属性
获取或设置应用于DataGridview的行单元格的默认样式。
private void Form1_Load(object sender, EventArgs e)
{
string str = "server=192.168.100.222;user=sa;pwd=p@ssw1rd;database=pwd1";
SqlConnection mycon = new SqlConnection(str);
try
{
mycon.Open();
DataSet mydt = new System.Data.DataSet();
SqlDataAdapter mydpt = new SqlDataAdapter("select * from book",mycon);
mydpt.Fill(mydt);
dataGridView1.DataSource = mydt.Tables[0];
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
if (i % 2 == 0)
{
this.dataGridView1.Rows[i].DefaultCellStyle.BackColor = Color.Beige;
}
else
{
this.dataGridView1.Rows[i].DefaultCellStyle.BackColor = Color.Red;
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
mycon.Close();
}
}