2010-06-09 6 views
1

DataGrid의 셀에 bool 필드가 있습니다. 내가하고 싶은 것은 진실은 빨간색, 거짓은 녹색으로 색을 칠하는 것입니다.C# Datagrid의 값을 기반으로 행 색상 변경

어떻게하면 C# Datagrid로이 작업을 수행 할 수 있습니까?

+1

이 윈도우 폼, ASP.NET, 실버 라이트, WPF인가 ...? –

+0

Winforms C# Datagrid Desktop. – Ricky

답변

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; 
      } 
     } 
    } 
} 
관련 문제