根据C#Datagrid中的值更改行颜色

时间:2010-06-09 18:06:33

标签: c# gridview datagridview datagrid

我在数据网格的单元格中有一个bool字段。我想要做的是用红色为真色而用绿色为假色。

如何使用C#Datagrid执行此操作?

1 个答案:

答案 0 :(得分:2)

使用cellformat事件可以帮助您,本示例可以帮助您:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace CSCellFormat
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        DataTable dt = new DataTable();
        private void Form1_Load(object sender, EventArgs e)
        {
            String strConn = "Server = .;Database = AdventureWorks; Integrated Security = SSPI;";
            SqlConnection conn = new SqlConnection(strConn);
            SqlDataAdapter da = new SqlDataAdapter("Select * from HumanResources.Employee", conn);
            da.Fill(dt);
            dataGridView1.DataSource = dt;
        }
        private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            DataRowView drv;
            if (e.RowIndex >= 0)
            {
                drv = dt.DefaultView[e.RowIndex];
                Color c;
                if (drv["Gender"].ToString() == "M")
                {
                    c = Color.LightBlue;
                }
                else
                {
                    c = Color.Pink;
                }
                e.CellStyle.BackColor = c;
            }
        }
    }
}