C# Datagridview布尔列条件

C# Datagridview布尔列条件,c#,C#,关于以表格形式显示数据库表内容的Datagridview,如果表中的一列为布尔类型,如何根据布尔值更改单元格颜色?您可能希望这样做:如果单元格为真,将单元格颜色更改为绿色,否则(如果为假)将颜色更改为红色 for(int i ==0;i<Totalrows;i++) { if(dataGridView1.Rows[i].Cells[columnIndex].Equals(True){ { dataGridView1.Rows[i].Cells[col

关于以表格形式显示数据库表内容的Datagridview,如果表中的一列为布尔类型,如何根据布尔值更改单元格颜色?

您可能希望这样做:如果单元格为真,将单元格颜色更改为绿色,否则(如果为假)将颜色更改为红色

for(int i ==0;i<Totalrows;i++)
{    
    if(dataGridView1.Rows[i].Cells[columnIndex].Equals(True){
    {
        dataGridView1.Rows[i].Cells[columnIndex].Style.BackColor = Color.Green;
    }
    else
    {
        dataGridView1.Rows[i].Cells[columnIndex].Style.BackColor = Color.Red;
    }
}

for(int i==0;i您可以遍历数据表中的数据并修改相应单元格的背景色

这里我们使用localdb进行测试,因为没有布尔类型,所以我们以nchar为例

// use SqlDataAdapter to get data from database
using (SqlConnection conn = new SqlConnection(@"connection string"))
{
    SqlDataAdapter sda = new SqlDataAdapter("Select * From Test", conn);
    DataSet Ds = new DataSet();
    sda.Fill(Ds, "TestTable");

    // traverse the datatable
    foreach (DataRow row in Ds.Tables[0].Rows)
    {
        // add new row
        int index = dataGridView1.Rows.Add();
        dataGridView1.Rows[index].Cells["Column1"].Value = row["Id"];
        dataGridView1.Rows[index].Cells["Column2"].Value = row["Status"]; // true/false
        dataGridView1.Rows[index].Cells["Column2"].Style.BackColor = row["Status"].ToString().Trim() == "True" ? Color.Green : Color.Red;
    }
}

您可以添加CellPaint事件

private void dataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
        {
            if (e.RowIndex >= 0 && e.ColumnIndex == 7 && Convert.ToString(e.Value.ToString()) == "True")
            {
                e.PaintBackground(e.ClipBounds, false);
                dataGridView1[e.ColumnIndex, e.RowIndex].ToolTipText = e.Value.ToString();
                PointF p = e.CellBounds.Location;
                p.X += 24;
                string path = "C:\\Users\\khali\\Desktop\\checkmark_18px.png";
                e.Graphics.DrawImage(Image.FromFile(path), e.CellBounds.X, e.CellBounds.Y, 25, 16);
                e.Handled = true;
            }
            else if (e.RowIndex >= 0 && e.ColumnIndex == 7 && Convert.ToString(e.Value.ToString()) == "False")
            {
                e.PaintBackground(e.ClipBounds, false);
                dataGridView1[e.ColumnIndex, e.RowIndex].ToolTipText = e.Value.ToString();
                PointF p = e.CellBounds.Location;
                p.X += 24;
                 string path = "C:\\Users\\khali\\Desktop\\delete_100px.png";
                e.Graphics.DrawImage(Image.FromFile(path), e.CellBounds.X, e.CellBounds.Y, 25, 16);

                 e.Handled = true;
            }
        }

请出示您的代码,以及您试图回避的问题。这是否回答了您的问题?