如果datagridview中的列值为true,则更改行颜色。 [英] Changing row color if column value from datagridview is true.
问题描述
如何在条件语句中使用名为posted的datagridview中显示的数据库中的列,当值为true / 1时,应将行的颜色更改为红色。
我尝试了什么:
foreach(dataGridViewRow Myrow in dataGridView1.Rows)
{
if(Convert.ToInt32(Myrow .Cells [posted]。Value == 1)
{
Myrow .DefaultCellStyle.BackColor = Color.Red;
}
else
{
Myrow .DefaultCellStyle.BackColor = Color.Green;
}
}
我也尝试使用:
if(Myrow.Cells [posted]。值== 1)
它正在工作但是所有的行都是红色的。它忽略了列的值,即使它的真或假。
你应该试试这个...
private void dataGridView1_CellFormatting( object sender,DataGridViewCellFormattingEventArgs e)
{
DataGridViewRow oRow = dataGridView1.Rows [e.RowIndex];
if (dataGridView1.Columns [e.ColumnIndex] .Name == 已发布&& e.Value == 1 ){
oRow.DefaultCellStyle .BackColor = Color.Red;
}
else
{
oRow.DefaultCellStyle.BackColor = Color.Green;
}
}
设置一个单元格的颜色:
private void myDataGridView_CellFormatting( object sender ,DataGridViewCellFormattingEventArgs e)
{
if (e.ColumnIndex == 1 )
{
var check = myDataGridView.Rows [e.RowIndex] .Cells [e.ColumnIndex] .Value;
if (check!= null &&( bool )check == false )
{
e.CellStyle.BackColor = Color.Red ;
}
}
}
How can I use a column in my database shown in my datagridview named "posted" in a conditional statement that when the value is true/1 it should change the rows' color into red.
What I have tried:
foreach (DataGridViewRow Myrow in dataGridView1.Rows)
{
if (Convert.ToInt32(Myrow .Cells["posted"].Value==1)
{
Myrow .DefaultCellStyle.BackColor = Color.Red;
}
else
{
Myrow .DefaultCellStyle.BackColor = Color.Green;
}
}
I also tried to use:
if (Myrow.Cells["posted"].Value==1)
It is working but all of the rows are red. and it disregards the value of column posted even if its true or false.
DataGridView.CellFormatting Event (System.Windows.Forms)[^]
You should try this...
private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e) { DataGridViewRow oRow = dataGridView1.Rows[e.RowIndex]; if(dataGridView1.Columns[e.ColumnIndex].Name == "posted" && e.Value == 1) { oRow.DefaultCellStyle.BackColor = Color.Red; } else { oRow.DefaultCellStyle.BackColor = Color.Green; } }
This sets the color of one Cell:
private void myDataGridView_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e) { if (e.ColumnIndex == 1) { var check = myDataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex].Value; if (check != null && (bool)check == false) { e.CellStyle.BackColor = Color.Red; } } }
这篇关于如果datagridview中的列值为true,则更改行颜色。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!