如何在datagridview中设置单元格bg颜色
问题描述:
您好先生,
i我从数据库中获取数据。
我在这里尝试过 -
Hello Sir,
i am fetching data from database.
I have tried upto here-
private void button1_Click(object sender, EventArgs e)
{
try
{
con.Open();
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = con;
cmd.CommandText = "select * from School";
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
dataGridView1.DataSource = dt;
}
catch (Exception ex)
{
MessageBox.Show("Error " + ex);
}
con.Close();
}
请告诉我如何显示单元格颜色为红色(如果值为0)或绿色(如果价值是1)。
我尝试过:
Sir请告诉我如何从datagridview获取单元格值。
Please advise me how can i show then cells color is red (if value is 0) or green(if value is 1).
What I have tried:
Sir please advise me how to get the cells value from datagridview.
答
试试这个:
Try this:
private void DataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
{
var dgv = (DataGridView) sender;
if (e.RowIndex < 0)
return;
var rowCurrent = ((DataRowView) dgv.Rows[e.RowIndex].DataBoundItem).Row;
e.CellStyle.BackColor = rowCurrent["yourValue"].ToString() == "0"
? Color.White
: Color.Red;
}
每个datagridview都有行和列。 yourValue表示要检查的列的数据表名称
Each datagridview has rows and columns. "yourValue" means the datapropertyname of the column you want to check