Winform DataGrid设计三步曲之二如何在DataGrid中加入ComboBox控件

  C#类库中的DataGrid控件功能非常强大,基本上可以应对一般的表格处理,但是对于特殊的要求,比如在DataGrid中加入单选框(ChechBox)和多选下拉菜单(ComboBox)时就要自己写一些代码了,在Framework1.1中的DataGrid并没有提供这方面的功能。下面介绍一种在DataGrid中加入ComboBox的方法。
1.      首先设置DataGrid的TableStyle
2.      然后利用DataGridTextBoxColumn中的TextBox.Controls属性把ComBoBox加入
3.      最后编写ComboBox的comboBox_SelectedIndexChanged事件,使修改可以保存回DataGrid的相应行。
        如果对于TableStyle不太清楚,请参看我的前一篇文章
下面是程序的完整例子,在vs2003中测试通过,代码说明在程序中,关于TableStyle的说明请参看上一篇文章。添加ComboBox的代码主要在InitDataTable()函数中。
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
 
namespace DataGridBackColor
{
     ///<summary>
     /// Form1 的摘要描述。
     ///</summary>
     public class Form1 : System.Windows.Forms.Form
     {
         private System.Windows.Forms.DataGrid dataGrid;
         private System.Windows.Forms.DataGridTableStyle TableStyle;
         private System.Windows.Forms.DataGridBoolColumn Status;
         private System.Windows.Forms.DataGridTextBoxColumn DataGridTextBox1;
         private System.Windows.Forms.DataGridTextBoxColumn DataGridTextBox2;
         private System.Windows.Forms.DataGridTextBoxColumn DataGridComboBox;
         ///<summary>
         ///设计工具所需的变数。
         ///</summary>
         private System.ComponentModel.Container components = null;
 
         public Form1()
         {
              //
              // 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()
         {
              System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(Form1));
              this.dataGrid = new System.Windows.Forms.DataGrid();
              this.TableStyle = new System.Windows.Forms.DataGridTableStyle();
              this.Status = new System.Windows.Forms.DataGridBoolColumn();
              this.DataGridTextBox1 = new System.Windows.Forms.DataGridTextBoxColumn();
              this.DataGridTextBox2 = new System.Windows.Forms.DataGridTextBoxColumn();
              this.DataGridComboBox = new System.Windows.Forms.DataGridTextBoxColumn();
              ((System.ComponentModel.ISupportInitialize)(this.dataGrid)).BeginInit();
              this.SuspendLayout();
              //
              // dataGrid
              //
              this.dataGrid.CaptionText = "DataGrid Example";
              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(408, 238);
              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.DataGridTextBox1,
                                                                                                                        this.DataGridTextBox2,
                                                                                                                        this.DataGridComboBox});
              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.RowHeadersVisible = false;
              this.TableStyle.SelectionBackColor = System.Drawing.Color.LightSkyBlue;
              this.TableStyle.SelectionForeColor = System.Drawing.Color.WhiteSmoke;
              //
              // Status
              //
              this.Status.AllowNull = false;
              this.Status.FalseValue = false;
              this.Status.HeaderText = "Status";
              this.Status.MappingName = "";
              this.Status.NullText = "";
              this.Status.NullValue = ((object)(resources.GetObject("Status.NullValue")));
              this.Status.TrueValue = true;
              this.Status.Width = 40;
              //
              // DataGridTextBox1
              //
              this.DataGridTextBox1.Format = "";
              this.DataGridTextBox1.FormatInfo = null;
              this.DataGridTextBox1.HeaderText = "TextBox1";
              this.DataGridTextBox1.MappingName = "";
              this.DataGridTextBox1.NullText = "";
              this.DataGridTextBox1.ReadOnly = true;
              this.DataGridTextBox1.Width = 75;
              //
              // DataGridTextBox2
              //
              this.DataGridTextBox2.Format = "";
              this.DataGridTextBox2.FormatInfo = null;
              this.DataGridTextBox2.HeaderText = "TextBox2";
              this.DataGridTextBox2.MappingName = "";
              this.DataGridTextBox2.NullText = "";
              this.DataGridTextBox2.Width = 75;
              //
              // DataGridComboBox
              //
              this.DataGridComboBox.Format = "";
              this.DataGridComboBox.FormatInfo = null;
              this.DataGridComboBox.HeaderText = "ComboBox";
              this.DataGridComboBox.MappingName = "";
              this.DataGridComboBox.NullText = "";
              this.DataGridComboBox.Width = 75;
              //
              // Form1
              //
              this.AutoScaleBaseSize = new System.Drawing.Size(5, 15);
              this.ClientSize = new System.Drawing.Size(408, 238);
              this.Controls.Add(this.dataGrid);
              this.Name = "Form1";
              this.Text = "DataGrid Example";
              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 Form1());
         }
 
         #region User Variable
         private DataTable UserTable = null;
         private DataView UserView = null;
         #endregion
 
         #region comboBox Event
         private void Form1_Load(object sender, System.EventArgs e)
         {
              try
              {
                  InitDataTable();
                  InitDataView();
                  InitDataGrid();
                  InitData();
              }
              catch( Exception ex )
              {
                  MessageBox.Show( ex.Message );
              }
         }
        
         private void comboBox_SelectedIndexChanged(object sender , System.EventArgs e)
         {
              //将修改写回dataGrid的相应行
              if( dataGrid != null )
              {
                  dataGrid[dataGrid.CurrentCell] = ((ComboBox)sender).SelectedItem.ToString();
              }
         }
         #endregion
 
         private void InitDataTable()
         {
              UserTable = new DataTable("UserTable");
              DataColumn[] d = new DataColumn[4];
              d[0] = new DataColumn("d0",typeof(bool));
              d[1] = new DataColumn("d1",typeof(string));
              d[2] = new DataColumn("d2",typeof(string));
              d[3] = new DataColumn("d3",typeof(string));
              UserTable.Columns.AddRange( d );
 
              TableStyle.MappingName = "UserTable";
              Status.MappingName = "d0";
              DataGridTextBox1.MappingName = "d1";
              DataGridTextBox2.MappingName = "d2";
              DataGridComboBox.MappingName = "d3";
 
              //创建一个新的ComboBox控件并设置其基本属性
              ComboBox comboBox = new ComboBox();
              comboBox.Items.AddRange( new object[]{ "Choose1" , "Choose2" , "Choose3" });
              comboBox.DropDownStyle = ComboBoxStyle.DropDownList;
              comboBox.Dock = DockStyle.Fill;
              DataGridComboBox.TextBox.Controls.Add( comboBox );//comboBox加入DataGrid的相应行
 
              //关联comboBoxSelectedIndexChanged事件
              comboBox.SelectedIndexChanged += new EventHandler(comboBox_SelectedIndexChanged);
         }
 
         private void InitDataView()
         {
              UserView = new DataView();
              UserView.Table = UserTable;
              UserView.AllowNew = false;
         }
 
         private void InitDataGrid()
         {
              dataGrid.DataSource = UserView;
         }
 
         private void InitData()
         {
              DataRow r = null;
              for( int count = 1 ; count < 4 ; count++ )
              {
                  r = UserTable.NewRow();
                  r[0] = true;
                  r[1] = "TextBox1" + count.ToString();
                  r[2] = "TextBox2" + count.ToString();
                  r[3] = "Choose" + count.ToString();
                  UserTable.Rows.Add( r );
              }
         }
     }
}
运行结果如下:
 
        在有些时候,DataGrid中不同行的值要以不同的颜色显示出来,比如告警,不同告警的背景色要不同,在下一篇文章中,我将介绍一下如何修改DataGrid的背景色问题。

posted on 2007-01-25 17:27  玄新  阅读(595)  评论(0编辑  收藏  举报

导航