【问题标题】:Change row color based in a value in the C# Datagrid根据 C# Datagrid 中的值更改行颜色
【发布时间】:2011-03-01 19:32:57
【问题描述】:

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

如何使用 C# Datagrid 做到这一点?

【问题讨论】:

  • 这是 Windows 窗体、ASP.NET、Silverlight、WPF、...?
  • Winforms C# Datagrid 桌面。

标签: c# gridview datagridview datagrid


【解决方案1】:

使用 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;
            }
        }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-07-29
    • 2018-05-12
    • 2010-12-03
    • 1970-01-01
    • 2022-01-12
    相关资源
    最近更新 更多