首 页 | 新 闻 | 技术中心 | 第二书店 | 《程序员》 | 《开发高手》 | 社 区 | 黄 页 | 人 才
移 动专 题SUNIBM微 软微 创精 华Donews人 邮
我的技术中心 
我的分类 我的文档
全部文章 发表文章
专栏管理 使用说明



 RSS 订阅 
最新文档列表
Windows/.NET
.NET  (rss)    
Visual C++  (rss)    
Delphi  (rss)    
Visual Basic  (rss)    
ASP  (rss)    
JavaScript  (rss)    
Java/Linux
Java  (rss)    
Perl  (rss)    
综合
其他开发语言  (rss)    
文件格式  (rss)    
企业开发
游戏开发  (rss)    
网站制作技术  (rss)    
数据库
数据库开发  (rss)    
软件工程
其他  (rss)    

积极原创作者 
yjz0065 (115)
iiprogram (70)
ShowLong (2)
coofucoo (106)
psyl (153)
capsicum29 (8)
qdzx2008 (51)
cyp403 (16)
lphpc (31)
smallnest (63)
CSDN - 文档中心 - .NET 阅读:4100   评论: 3    参与评论
标题   DataGrid使用技巧     选择自 hedonister 的 Blog
关键字   DataGrid使用技巧
出处  

DataGrid使用技巧

-------如何屏蔽单元格输入

       有时候听有些朋友抱怨.NETDataGrid不是很好用。就我个人的体会,DataGrid的功能非常强大,可以使我们随心所欲的完成各种各样的工作,可惜就是实现起来不够简单明了。我对平时经常碰到的一些问题积累了一些解决的方法,现在把它们总结一下供大家参考。

       比较经常碰到的一个问题是:我们希望DataGrid的某一列只能输入特定的文本,比如:不能输入数字。下面的例子说明如何实现这种功能。
       
新建一个Window应用程序,加入一个DataGridSqlConnection,连接SQL数据库NorthWind

namespace WindowsApplication1
{
public class Form1 : System.Windows.Forms.Form
{
          private myDataGrid dataGrid1;
          private System.Data.SqlClient.SqlConnection sqlConnection1;
           //
加入全局变量oldValue,用它表示单元格原来的文本。
          private string oldValue;

          private void Form1_Load(object sender, System.EventArgs e)
        {
        oldValue="";
        SqlDataAdapter sda=new SqlDataAdapter("select LastName,FirstName from employees",this.sqlConnection1);
        DataSet ds=new DataSet();
        sda.Fill(ds,"employees");
        DataGridTableStyle ats=new DataGridTableStyle();
        ats.MappingName="employees";
        DataGridColorColumn dcs1=new DataGridColorColumn();
        dcs1.HeaderText="lastname";
        ats.GridColumnStyles.Add(dcs1);
        DataGridTextBoxColumn dcs2=new DataGridTextBoxColumn();
        dcs2.HeaderText="firstname";
        dcs2.MappingName="FirstName";
        dcs2.TextBox.TextChanged+=new EventHandler(DataGridTextChanged);
        dcs2.TextBox.Enter+=new EventHandler(DataGridTextBox_Enter);
        ats.GridColumnStyles.Add(dcs2);
        this.dataGrid1.TableStyles.Add(ats);
        this.dataGrid1.DataSource=ds;
        this.dataGrid1.DataMember="employees";  
        }
       

       private void DataGridTextBox_Enter(object sender,EventArgs e)
       {
          //
当某一单元格获得焦点时,记录单元格的文本
         oldValue=((DataGridTextBoxColumn) this.dataGrid1.TableStyles[0].GridColumnStyles[1]).TextBox.Text;
       }
      

       private void DataGridTextChanged(object sender,EventArgs e)
      {
           int index=0;
           string str=((DataGridTextBoxColumn)this.dataGrid1.TableStyles[0].GridColumnStyles[1]).TextBox.Text;
           //
当单元格的文本改变时,检验是否有非法字符
            while(index<str.Length)
           {
           //
如果发现数字,显示错误信息并将单元格还原为原内容
           if (Char.IsDigit(str,index))
           {
            MessageBox.Show("
不能输入数字,请重新输入");
            ((DataGridTextBoxColumn)this.dataGrid1.TableStyles[0].GridColumnStyles[1]).TextBox.Text=oldValue;
            return;
            }
             index++;
        }
}
}

------------如何实现多行表头

       有时候听有些朋友抱怨.NETDataGrid不是很好用。就我个人的体会,DataGrid的功能非常强大,可以使我们随心所欲的完成各种各样的工作,可惜就是实现起来不够简单明了。我对平时经常碰到的一些问题积累了一些解决的方法,现在把它们总结一下供大家参考。
      
比较经常碰到的一个问题是:我们希望DataGrid的表头是多行的(图1)。我在网上找了很久也找不到解决的方法,后来想到了DataGridCaptionTextCaptionFont属性。于是我就想能不能在Caption的显示区域画出多行表头。下面的示例代码实现了这个想法,结果如图1所示。

       首先需要编写一个类来表示自画的表头,这个类将记录表头的显示文本、图标和属于它管辖的列的信息。

                  //表头类
                  public class TopHeaderColumn
                  {
                         public TopHeaderColumn()
                         {
                         this.columnCollection=new ArrayList();
                         }
                          private string caption;
                        //
表头的显示文本 
                          public string Caption
                          {
                            get {return caption;}
                            set {caption=value;}
                          }
                         private ArrayList columnCollection;
                        //
用来记录属于表头管辖的各列的信息(通过往集合里添加object
                         public ArrayList ColumnCollection
                         {
                          get {return this.columnCollection;}
                          set {this.columnCollection=value;}
                          }
                         private int width;
                         //
表头的宽度
                         public int Width
                         {
                          get {return width;}
                          set {width=value;}
                          }
                         private Image image=null;
                         //
表头的图标
                         public Image Image
                         {
                           get {return image;}
                           set {image=value;}
                          }

                    }
      
另外,因为以后的代码需要DataGrid水平滚动条的位置,而DataGrid无法取得水平滚动条的位置,所以需要对DataGrid做一点修改。
                   public class myDataGrid:DataGrid
                   {
  
                       public ScrollBar HScrollBar
                       {
                          get {return this.HorizScrollBar;}
                       }
                   }

       好了,可以工作了。新建一个Window应用程序,加入一个myDataGridSqlConnectionImageList,连接SQL数据库NorthWind。当然,还得加入上面的代码
                  
               namespace WindowsApplication1
              {
                       public class Form1 : System.Windows.Forms.Form
                       {
                          private System.Data.SqlClient.SqlConnection sqlConnection1;
                          private myDataGrid dataGrid1;
                          private ArrayList al;
                          private System.Windows.Forms.ImageList imageList1;
                          \\
InitializeComponent()里加入这一句:this.dataGrid1 = new myDataGrid(),并根据你的需要设置其他的DataGrid属性。注意,CaptionVisible必须设为true,CaptionText=""
                          private void Form1_Load(object sender, System.EventArgs e)
                          {
                             SqlDataAdapter da=new SqlDataAdapter("select lastname, firstname, Address,City from employees",this.sqlConnection1);
                             DataSet ds=new DataSet();
                             da.Fill(ds,"employees");
                             this.dataGrid1.DataSource=ds;
                             this.dataGrid1.DataMember="employees";

                             //设置DataGrid的各列
                             DataGridTextBoxColumn c1=new DataGridTextBoxColumn();
                             DataGridTextBoxColumn c2=new DataGridTextBoxColumn();
                             DataGridTextBoxColumn c3=new DataGridTextBoxColumn();
                             DataGridTextBoxColumn c4=new DataGridTextBoxColumn();
                             c1.MappingName="lastname";
                             c2.MappingName="firstname";
                             c3.MappingName="Address";
                             c4.MappingName="City";
                             c1.HeaderText="lastname";
                             c2.HeaderText="firstname";
                             c3.HeaderText="Address";
                             c4.HeaderText="City";
               c1.WidthChanged+=new EventHandler(this.abc);//
列的宽变动时调整表头宽度
                             c2.WidthChanged+=new EventHandler(this.abc);
                             c3.WidthChanged+=new EventHandler(this.abc);
                             c4.WidthChanged+=new EventHandler(this.abc);

                             DataGridTableStyle dts=new DataGridTableStyle();
                             dts.GridColumnStyles.Add(c1);
                             dts.GridColumnStyles.Add(c2);
                             dts.GridColumnStyles.Add(c3);
                             dts.GridColumnStyles.Add(c4);

                             dts.MappingName="employees";   this.dataGrid1.TableStyles.Add(dts);

                              //建立自画的表头类并将它们加入集合al   
                             al=new ArrayList();
                             TopHeaderColumn tc1=new TopHeaderColumn();
                             tc1.Caption="Name";
                             tc1.Image=this.imageList1.Images[0];
                             tc1.ColumnCollection.Add(0);//
记录它管辖的列的index
                             tc1.ColumnCollection.Add(1);
                             tc1.Width=c1.Width+c2.Width;

                            TopHeaderColumn tc2=new TopHeaderColumn();
                             tc2.Caption="Address";
                             tc2.ColumnCollection.Add(2);
                             tc2.ColumnCollection.Add(3);
                             tc2.Width=c3.Width+c4.Width;
   
                             al.Add(tc1);
                             al.Add(tc2);
                             this.dataGrid1.Paint += new System.Windows.Forms.PaintEventHandler(this.dataGrid1_Paint);
                          }

                         private void dataGrid1_Paint(object sender, System.Windows.Forms. PaintEventArgs e)
                        {
                           int x=0;
                           //
计算出第一个表头的左边距
                           int left=this.dataGrid1.TableStyles[0].RowHeaderWidth-this.dataGrid1.HScrollBar.Value;
                           //
遍历表头集合al,画出表头   
                           foreach (object o in this.al)
                           {
                          //
计算出表头文字(文字居中)的左边距
                           x=left+(((TopHeaderColumn)o).Width-Convert.ToInt32(e.Graphics. MeasureString (((TopHeaderColumn)o).Caption, this.dataGrid1.CaptionFont). Width))/2;
                          //
完成表头绘制  
                          if (((TopHeaderColumn)o).Image!=null)
                          e.Graphics.DrawImage(((TopHeaderColumn)o).Image,x-imageList1.Images[0].Size.Width,0); 

                           e.Graphics.DrawString(((TopHeaderColumn)o).Caption,this.dataGrid1. CaptionFont,new SolidBrush(this.dataGrid1.CaptionForeColor),x,0);
                           if (x>0)
                           e.Graphics.DrawLine(new Pen(Color.Black,2),left-1,0,left-1,this.dataGrid1.Height);
                           //
计算出下一个表头的左边距
                           left+=((TopHeaderColumn)o).Width;
                           }
                           if (x<this.dataGrid1.Width)
                           e.Graphics.DrawLine(new Pen(Color.Black,2),left-1,0,left-1,this.dataGrid1.Height);  
                         }

                     private void abc(object sender,EventArgs e)
                     {
                       //
设置表头的宽度
                        foreach (object o in this.al)
                        {
                         ((TopHeaderColumn)o).Width=0;
                        foreach (int i in ((TopHeaderColumn)o).ColumnCollection)
                        {   ((TopHeaderColumn)o).Width+=this.dataGrid1.TableStyles[0].GridColumnStyles[i].Width;
                        }
                        }
                      }

                     private void dataGrid1_Scroll(object sender, System.EventArgs e)
                     {
                       this.dataGrid1.Refresh();
                     }

      上面的代码实现了两层表头,至于三层表头也同理。

      关于如何实现DataGrid多层表头,许多网友都提到,目前好像没有一种特别好的方便的方法。

--------如何实现下拉列表

       有时候听有些朋友抱怨.NETDataGrid不是很好用。就我个人的体会,DataGrid的功能非常强大,可以使我们随心所欲的完成各种各样的工作,可惜就是实现起来不够简单明了。我对平时经常碰到的一些问题积累了一些解决的方法,现在把它们总结一下供大家参考。
      
比较经常碰到的一个问题是:在编辑单元格内容时我们希望出现这样的下拉列表,如图1所示:


1

思路:
            1
写一个类comboForm表示下拉列表,类包含两个成员:Form窗体和DataGrid组件。
            2
写一个类NoKeyUpComboBox(继承ComboBox),目的是屏蔽WM_KEYUP消息,避免在按Tab键时出现问题。
            3
写一个继承于DataGridTextBoxColumn的类,命名为DataGridComboFormColumn。在类中加入一个ComboBox和一个comboForm,类实现下面几个功能:
            a
编辑单元格内容时显示组件NoKeyUpComboBox
            b ComboBox
下拉时显示下拉列表comboForm
            c
鼠标点击下拉列表时,隐藏comboForm并将用户选定的内容写入单元格(当然,你也可以设置其他隐藏下拉列表的操作,比如按回车键);
            d
下拉列表comboForm不具有焦点时隐藏。

代码:           
//comboForm
类:
 public class comboForm:Form
 {
  private DataGrid dataGrid;
  public DataGrid DataGrid
  {
   get {return dataGrid;}
   set {dataGrid=value;}
  }
  public comboForm()
  {
   this.FormBorderStyle=FormBorderStyle.None;
   this.StartPosition=FormStartPosition.Manual;
   dataGrid=new DataGrid();
   this.Controls.Add(dataGrid);
   dataGrid.Dock=DockStyle.Fill;
   dataGrid.CaptionVisible=false;
  }
 }

//NoKeyUpComboBox类:
public class NoKeyUpComboBox:ComboBox
 {
 const int WM_KEYUP=0x101;
  protected override void WndProc(ref Message msg)
  {
  if (msg.Msg==WM_KEYUP)
   return;
   base.WndProc(ref msg);
  }
 }

//DataGridComboFormColumn类:
 public class DataGridComboFormColumn:DataGridTextBoxColumn
 {
  private NoKeyUpComboBox comboBox;
  private CurrencyManager _source;
  private int rowNum;
  private comboForm frm;
  public comboForm Frm
  {
   get {return frm;}
  }
  //
我们将使用Index属性表示单元格内容与下拉列表的第Index列的内容相联系
  private int index;
  public int Index
  {
   get {return index;}
   set {index=value;}
  }
  
  public DataGridComboFormColumn()
  {
  frm=new comboForm();
  comboBox=new NoKeyUpComboBox();
  frm.Deactivate+=new EventHandler(frm_deactive);
  frm.DataGrid.Click+=new EventHandler(grid_click);
  this.comboBox.DropDown+=new EventHandler(comboBox_dropDown);
  this.comboBox.Leave+=new EventHandler(comboBox_leave);
  }
  //comboBox
不具有焦点时隐藏
  private void comboBox_leave(object sender,EventArgs e)
  {
  comboBox.Visible=false;
  }
  //
下拉列表--Frm不具有焦点时隐藏
  private void frm_deactive(object sender,EventArgs e)
  {
  frm.Hide();
  comboBox.Visible=false;
  }
   //comboBox
下拉时显示下拉列表--Frm
  private void comboBox_dropDown(object sender,EventArgs e)
  {
   //
在这里您还可以根据下拉列表的长与宽是否超出屏幕设置下拉列表的位置
  frm.Left=comboBox.PointToScreen(new Point(0,comboBox.Height)).X;
  frm.Top=comboBox.PointToScreen(new Point(0,comboBox.Height)).Y;
  frm.Show();
  frm.BringToFront();
  }
  //
点击下拉列表的DataGrid时,将选中的内容写入单元格并隐藏下拉列表--Frm
  private void grid_click(object sender,EventArgs e)
  {
  BindingManagerBase cm=frm.BindingContext[Frm.DataGrid.DataSource, frm.DataGrid.DataMember];
  comboBox.Text=((DataRowView)cm.Current)[index].ToString();
  this.TextBox.Text=((DataRowView)cm.Current)[index].ToString();
  frm.Hide();
  comboBox.Visible=false;
  this.SetColumnValueAtRow(_source,rowNum,this.TextBox.Text);
  }
  //
重载Edit方法,使用comboBox代替TextBox
  protected override void Edit(CurrencyManager dataSource,int rowNum,Rectangle bounds,bool readOnly,string instanttext,bool cellVisible)
  {
   base.Edit(dataSource,rowNum,bounds,readOnly,instanttext,cellVisible);
   comboBox.Parent=this.TextBox.Parent;
   comboBox.Left=this.TextBox.Left-2;
   comboBox.Top=this.TextBox.Top-2;
   comboBox.Size=new Size(this.TextBox.Width,this.comboBox.Height);
   comboBox.Text=this.TextBox.Text;

   this.TextBox.Visible=false;
   comboBox.Visible=true;
   comboBox.BringToFront();
   comboBox.Focus();
   _source=dataSource;
   this.rowNum=rowNum;
  }
 }

      下面的例子说明了如何使用DataGridComboFrom类:
新建一个Windows 应用程序,加入SqlConnection,连接SQL数据库Northwind,加入下面代码。

private void Form1_Load(object sender, System.EventArgs e)
  {
  SqlDataAdapter da=new SqlDataAdapter("select ProductName from Products",this.sqlConnection1);
  DataSet ds=new DataSet();
   da.Fill(ds,"products");
   DataSet ds_Combo=new DataSet();
   da.SelectCommand=new SqlCommand("select ProductName,QuantityPerUnit,UnitPrice from Products",this.sqlConnection1);
   da.Fill(ds_Combo,"products");

   DataGridTableStyle dts=new DataGridTableStyle();
   dts.MappingName="products";
   myDataGridColumn col=new myDataGridColumn();
   col.MappingName="ProductName";
   col.Width=100;
   col.Index=0;
   col.HeaderText="ProductName";

   col.Frm.DataGrid.DataSource=ds_Combo;//设置下拉列表的数据源
   col.Frm.DataGrid.DataMember="products";
   dts.GridColumnStyles.Add(col);
   
   this.dataGrid1.TableStyles.Add(dts);
   this.dataGrid1.SetDataBinding(ds,"products");
  }

------------如何在DataGrid中显示来自不同DataTable的数据

       有时候听有些朋友抱怨.NETDataGrid不是很好用。就我个人的体会,DataGrid的功能非常强大,可以使我们随心所欲的完成各种各样的工作,可惜就是实现起来不够简单明了。我对平时经常碰到的一些问题积累了一些解决的方法,现在把它们总结一下供大家参考。
      
比较经常碰到的一个问题是:如何将来自不同DataTable的字段组合显示在DataGrid中?当然,可以将数据合并到一个DataTable中,但有时候由于其他限制不能将数据合并,下面提供了一种在DataGrid中显示来自不同DataTable(同在一个DataSet中)的数据的方法。

    数据在DataSet中的结构

    我们希望数据在DataGrid中如下图显示

    下面用一个例子说明如何实现将来自不同DataTable的数据显示在DataGrid中。

     基本思路:很显然,DataGrid不能同时绑定两个DataTable,那么,要使它显示两个不同DataTable的数据,就只有在DataGridColumn中下功夫了。以上面的结构为例,我们建立一个继承DataGridTextBoxColumn的类DataGridJoinColumn,重载GetColumnValueAtRow方法。这个类要实现的功能是:数据源是DataTable1,返回值是DataTable1.EmployeeID对应的DataTable2.LastNameDataTable2.FirstNameDataTable1.EmployeeIDDataTable2.EmployeeID1对多联系,我们将这个联系添加到DataSet中,就可以通过GetParentRow(relation)方法取得DataTable1.EmployeeID对应的DataTable2.LastNameDataTable2.FirstName的值。具体代码如下:

     public class JoinTextBoxColumn : DataGridTextBoxColumn
     {
         string relation; //
表示DataTable1.EmployeeIDDataTable2.EmployeeID1对多联系
         DataColumn col; //
表示返回DataTable2的列
         public JoinTextBoxColumn(string relation,DataColumn col )
         {
         this.relation=relation;
         this.col=col;
         base.ReadOnly=true;
         }
         protected override object GetColumnValueAtRow(CurrencyManager cm,int RowNum)
         {
             try
             {
              DataRow dr=((DataView)cm.List)[RowNum].Row;
              DataRow parentdr=dr.GetParentRow(relation);
              return parentdr[col]; //
返回值是DataTable1.EmployeeID对应的LastNameFirstName
             }
             catch
             {
             return "";  //
避免在添加新行时发生异常
             }
        }
        protected override bool Commit(CurrencyManager cm,int RowNum)
        {
            return false;
        }
        public new bool ReadOnly
       {
            get {return true;}
       }
   }

       下面的代码说明了如何使用类DataGridJoinColumn。新建一个Windows程序,加入一个DataGrid和一个SqlConnection,连接数据库NorthWind Form_Load中加入下面代码:

     private void Form1_Load(object sender, System.EventArgs e)
     {
         SqlDataAdapter sda1=new SqlDataAdapter("select EmployeeID,LastName,FirstName from Employees",this.sqlConn);
         SqlDataAdapter sda3=new SqlDataAdapter("select OrderID,EmployeeID,OrderDate,RequiredDate from Orders",this.sqlConn);

         ds=new DataSet();
         sda1.Fill(ds,"emp");
         sda3.Fill(ds,"ord");

         ds.Relations.Add("ord_emp",ds.Tables["emp"].Columns["EmployeeID"],ds.Tables["ord"].Columns["EmployeeID"]);
   
         ds.Tables["ord"].Columns.Add("lastName",typeof(string));
         ds.Tables["ord"].Columns.Add("firstName",typeof(string));
   
         DataGridTableStyle dt=new DataGridTableStyle();
         DataGridColumnStyle dc;
           
        dc=new DataGridTextBoxColumn();
        dc.MappingName="OrderID";
        dc.HeaderText="OrderID";
        dt.GridColumnStyles.Add(dc);

        dc=new DataGridTextBoxColumn();
        dc.MappingName="EmployeeID";
        dc.HeaderText="EmployeeID";
        dt.GridColumnStyles.Add(dc);

        dc=new JoinTextBoxColumn("ord_emp",ds.Tables["emp"].Columns["firstName"]);
        dc.MappingName="firstName";
        dc.HeaderText="firstName";
        dt.GridColumnStyles.Add(dc);