2010-06-09 95 views
1

在datagrid的单元格中有一个bool字段。我想要做的是用红色对行进行着色,对于错误则为绿色。更改基于C#Datagrid中的值的行颜色

我该怎么用C#Datagrid做这件事?

+1

这是Windows窗体,ASP.NET,Silverlight的,WPF,...? – 2010-06-09 18:09:16

+0

Winforms C#Datagrid桌面。 – Ricky 2010-06-09 18:26:07

回答

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