Winform DataGrid设计三步曲之三----如何改变DataGrid的背景色

来源:互联网 发布:一笔签名设计软件 编辑:程序博客网 时间:2024/05/17 20:02

 

                Winform DataGrid设计三步曲之三
                                        如何改变DataGrid的背景色
        在用DataGrid作为表格显示数据的时候,有时往往需要根据数据的内容来显示不同的颜色,比如作告警列表时,不同的告警要用不同的颜色表示。修改DataGrid背景色的方法很多,这里介绍一种使用DataGrid的TableStyle属性方法来修改背景色。大致过程如下:
1.      自定义DataGridColoredTextBoxColumn类,继承自DataGridTextBoxColumn
2.      重写(override) Paint方法
3.      DataGridColoredTextBoxColumn类替代程序中的DataGridTextBoxColumn
代码如下:代码说明详见代码中的注释,该程序在vs2003下测试通过。程序中用到了TableStyle,如果对于TableStyle不太清楚,请参看我的第一篇文章
                http://blog.csdn.net/tjvictor/archive/2007/01/20/1488549.aspx
程序中所有关于TableStyle的部分都没有加注释。程序的重点在于DataGridColoredTextBoxColumn 类的构造和Paint方法的重写。
代码如下:
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
 
namespace DataGridBackColor
{
     ///<summary>
     /// BackColorForm 的摘要描述。
     ///</summary>
     public class BackColorForm : System.Windows.Forms.Form
     {
         //定义DataGridColoredTextBoxColumn
         public class DataGridColoredTextBoxColumn : DataGridTextBoxColumn
         {
              //利用DataView来传递当前DataGrid中的数据
              public DataView dv = null;
 
              //重写Paint
              protected override void Paint(Graphics g, Rectangle bounds, CurrencyManager source, int rowNum, Brush backBrush, Brush foreBrush, bool alignToRight)
              {
                  try
                  {
                       //判断DataGrid中每行第一列的数据是否为如下的字符串
                       switch( dv[rowNum].Row[0].ToString() )
                       {
                           case "critical" : backBrush = Brushes.Red; break;//改变颜色
                           case "major" : backBrush = Brushes.Brown; break;//改变颜色
                           case "minor" : backBrush = Brushes.Orange; break;//改变颜色
                           case "warning" : backBrush = Brushes.YellowGreen; break;//改变颜色
                           default : break;
                       }
                  }
                  catch( Exception ex )
                  {
                       MessageBox.Show( ex.Message );
                  }
                  finally
                  {
                       //调用基类的Paint方法
                       base.Paint (g, bounds, source, rowNum, backBrush, foreBrush, alignToRight);
                  }
              }
         }
         private System.Windows.Forms.DataGrid dataGrid;
         private System.Windows.Forms.DataGridTableStyle TableStyle;
         private DataGridColoredTextBoxColumn Status;
         private DataGridColoredTextBoxColumn TextBox1;
         private DataGridColoredTextBoxColumn TextBox2;
        
         ///<summary>
         ///设计工具所需的变数。
         ///</summary>
         private System.ComponentModel.Container components = null;
 
         public BackColorForm()
         {
              //
              // Windows Form 设计工具支持的必要项
              //
              InitializeComponent();
 
              //
              // TODO: InitializeComponent 呼叫之后加入任何建构函式程序代码
              //
         }
 
         ///<summary>
         ///清除任何使用中的资源。
         ///</summary>
         protected override void Dispose( bool disposing )
         {
              if( disposing )
              {
                  if(components != null)
                  {
                       components.Dispose();
                  }
              }
              base.Dispose( disposing );
         }
 
         #region Windows Form 设计工具产生的程序代码
         ///<summary>
         ///此为设计工具支持所必须的方法 - 请勿使用程序代码编辑器修改
         ///这个方法的内容。
         ///</summary>
         private void InitializeComponent()
         {
              this.dataGrid = new System.Windows.Forms.DataGrid();
              this.TableStyle = new System.Windows.Forms.DataGridTableStyle();
              this.Status = new DataGridColoredTextBoxColumn();
              this.TextBox1 = new DataGridColoredTextBoxColumn();
              this.TextBox2 = new DataGridColoredTextBoxColumn();
              ((System.ComponentModel.ISupportInitialize)(this.dataGrid)).BeginInit();
              this.SuspendLayout();
              //
              // dataGrid
              //
              this.dataGrid.CaptionText = "BackColorForm";
              this.dataGrid.DataMember = "";
              this.dataGrid.Dock = System.Windows.Forms.DockStyle.Fill;
              this.dataGrid.HeaderForeColor = System.Drawing.SystemColors.ControlText;
              this.dataGrid.Location = new System.Drawing.Point(0, 0);
              this.dataGrid.Name = "dataGrid";
              this.dataGrid.Size = new System.Drawing.Size(292, 266);
              this.dataGrid.TabIndex = 0;
              this.dataGrid.TableStyles.AddRange(new System.Windows.Forms.DataGridTableStyle[] {
                                                                                                               this.TableStyle});
              //
              // TableStyle
              //
              this.TableStyle.AlternatingBackColor = System.Drawing.Color.Wheat;
              this.TableStyle.BackColor = System.Drawing.Color.LightGray;
              this.TableStyle.DataGrid = this.dataGrid;
              this.TableStyle.ForeColor = System.Drawing.Color.MidnightBlue;
              this.TableStyle.GridColumnStyles.AddRange(new System.Windows.Forms.DataGridColumnStyle[] {
                                                                                                                        this.Status,
                                                                                                                        this.TextBox1,
                                                                                                                        this.TextBox2});
              this.TableStyle.GridLineColor = System.Drawing.Color.Black;
              this.TableStyle.HeaderBackColor = System.Drawing.Color.LightBlue;
              this.TableStyle.HeaderForeColor = System.Drawing.SystemColors.ControlText;
              this.TableStyle.MappingName = "";
              this.TableStyle.SelectionBackColor = System.Drawing.Color.LightSkyBlue;
              this.TableStyle.SelectionForeColor = System.Drawing.Color.WhiteSmoke;
              //
              // Status
              //
              this.Status.Format = "";
              this.Status.FormatInfo = null;
              this.Status.HeaderText = "Status";
              this.Status.MappingName = "";
              this.Status.NullText = "";
              this.Status.Width = 75;
              //
              // TextBox1
              //
              this.TextBox1.Format = "";
              this.TextBox1.FormatInfo = null;
              this.TextBox1.HeaderText = "TextBox1";
              this.TextBox1.MappingName = "";
              this.TextBox1.NullText = "";
              this.TextBox1.Width = 75;
              //
              // TextBox2
              //
              this.TextBox2.Format = "";
              this.TextBox2.FormatInfo = null;
              this.TextBox2.HeaderText = "TextBox2";
              this.TextBox2.MappingName = "";
              this.TextBox2.NullText = "";
              this.TextBox2.Width = 75;
              //
              // BackColorForm
              //
              this.AutoScaleBaseSize = new System.Drawing.Size(5, 15);
              this.ClientSize = new System.Drawing.Size(292, 266);
              this.Controls.Add(this.dataGrid);
              this.Name = "BackColorForm";
              this.Text = "BackColorForm";
              this.Load += new System.EventHandler(this.Form1_Load);
              ((System.ComponentModel.ISupportInitialize)(this.dataGrid)).EndInit();
              this.ResumeLayout(false);
 
         }
         #endregion
 
         ///<summary>
         ///应用程序的主进入点。
         ///</summary>
         [STAThread]
         static void Main()
         {
              Application.Run(new BackColorForm());
         }
 
         #region User Variable
         private DataTable UserTable = null;
         private DataView UserView = null;
         #endregion
 
         private void Form1_Load(object sender, System.EventArgs e)
         {
              try
              {
                  InitDataTable();
                  InitDataView();
                  InitDataGrid();
                  InitData();
              }
              catch( Exception ex )
              {
                  MessageBox.Show( ex.Message );
              }
         }
        
         private void InitDataTable()
         {
              UserTable = new DataTable("UserTable");
              DataColumn[] d = new DataColumn[4];
              d[0] = new DataColumn("d0",typeof(string));
              d[1] = new DataColumn("d1",typeof(string));
              d[2] = new DataColumn("d2",typeof(string));
              UserTable.Columns.AddRange( d );
 
              TableStyle.MappingName = "UserTable";
              Status.MappingName = "d0";
              TextBox1.MappingName = "d1";
              TextBox2.MappingName = "d2";
         }
 
         private void InitDataView()
         {
              UserView = new DataView();
              UserView.Table = UserTable;
              UserView.AllowNew = false;
 
              //DataView赋给DataGridColoredTextBoxColumn类中的DataView变量
              Status.dv = UserView;
              TextBox1.dv = UserView;
              TextBox2.dv = UserView;
         }
 
         private void InitDataGrid()
         {
              dataGrid.DataSource = UserView;
         }
 
         private void InitData()
         {
              DataRow r = null;
              //Row 1
              r = UserTable.NewRow();
              r[0] = "critical";
              r[1] = "TextBox11";
              r[2] = "TextBox21";
              UserTable.Rows.Add( r );
              //Row 2
              r = UserTable.NewRow();
              r[0] = "major";
              r[1] = "TextBox12";
              r[2] = "TextBox22";
              UserTable.Rows.Add( r );
              //Row 3
              r = UserTable.NewRow();
              r[0] = "minor";
              r[1] = "TextBox13";
              r[2] = "TextBox23";
              UserTable.Rows.Add( r );
              //Row 4
              r = UserTable.NewRow();
              r[0] = "warning";
              r[1] = "TextBox14";
              r[2] = "TextBox24";
              UserTable.Rows.Add( r );
             
         }
     }
}
 
运行结果如下:
                至此,关于DataGrid的基本用法已经讲完了,DataGrid的功能不仅只是这些,以后我会继续追加关于DataGrid用法的文章。如果是想用ListBox来显示相应的数据并改变背景色的情况,请参见我的另一篇文章
                http://blog.csdn.net/tjvictor/archive/2007/01/20/1488378.aspx

 

原创粉丝点击