DataGrid相关知识总结(收集自各位老大处)

关于datagrid的问题,如何使行宽不可由用户更改。(即行宽固定,不能通过拖拉的方式改变)
定义DataGrid的时候就把宽度设定

   1<asp:boundcolumn ...=""> <headerstyle width="150px"></headerstyle>
   2
   3如何在winform中DataGrid点击某行,使数据实时显示在TEXTBOX中?   
   4datagrid的keypress事件中 
   5
   6textbox1.text=mydatagrid(mydatagrid.currentcell.rownumber,0)   
   7textbox2.text=mydatagrid(mydatagrid.currentcell.rownumber,1)   
   8........ 
   9
  10以此类推 
  11
  12namespace DataGridDoubleClick   
  13{   
  14using System;   
  15using System.Drawing;   
  16using System.Collections;   
  17using System.ComponentModel;   
  18using System.Windows.Forms;   
  19using System.Data; 
  20
  21public class Form1 : System.Windows.Forms.Form   
  22{   
  23private System.Windows.Forms.DataGrid dataGrid1;   
  24private DataSet myDataSet;   
  25DateTime gridMouseDownTime;   
  26private System.Windows.Forms.Label label1;   
  27  
  28private System.ComponentModel.Container components = null; 
  29
  30public Form1()   
  31{   
  32InitializeComponent();   
  33gridMouseDownTime = DateTime.Now;   
  34SetUp();   
  35} 
  36
  37private void SetUp()   
  38{   
  39// 用2个Table和1和Relation创建DataSet   
  40MakeDataSet();   
  41// 数据绑定   
  42dataGrid1.SetDataBinding(myDataSet, "Customers"); 
  43
  44//添加样式   
  45AddCustomDataTableStyle();   
  46} 
  47
  48private void MakeDataSet()   
  49{   
  50// 创建DataSet.   
  51myDataSet = new DataSet("myDataSet");   
  52  
  53// 创建2个DataTables.   
  54DataTable tCust = new DataTable("Customers");   
  55  
  56// 创建两个列,并添加到第一个表   
  57DataColumn cCustID = new DataColumn("custID");   
  58DataColumn cCustName = new DataColumn("custName");   
  59DataColumn cCurrent = new DataColumn("custCity");   
  60tCust.Columns.Add(cCustID);   
  61tCust.Columns.Add(cCustName);   
  62tCust.Columns.Add(cCurrent); 
  63
  64// 把tables添加到DataSet.   
  65myDataSet.Tables.Add(tCust);   
  66  
  67  
  68/* 计算tables.对每个客户,创建DataRow变量 */   
  69DataRow newRow1;   
  70  
  71// 添加记录到 Customers Table.   
  72for(int i = 1; i &lt; 4; i++)   
  73{   
  74newRow1 = tCust.NewRow();   
  75newRow1["custID"] = (100*i).ToString();   
  76tCust.Rows.Add(newRow1);   
  77} 
  78
  79tCust.Rows[0]["custName"] = "【孟宪会之精彩世界】";   
  80tCust.Rows[1]["custName"] = "net_lover";   
  81tCust.Rows[2]["custName"] = " http://xml.sz.luohuedu.net/ "; 
  82
  83  
  84tCust.Rows[0]["custCity"] = "北京";   
  85tCust.Rows[1]["custCity"] = "上海";   
  86tCust.Rows[2]["custCity"] = "河南";   
  87} 
  88
  89private void AddCustomDataTableStyle()   
  90{   
  91DataGridTableStyle ts1 = new DataGridTableStyle();   
  92ts1.MappingName = "Customers";   
  93// 设置属性   
  94ts1.AlternatingBackColor = Color.LightGray; 
  95
  96// 添加Textbox列样式,以便我们捕捉鼠标事件   
  97DataGridTextBoxColumn TextCol = new DataGridTextBoxColumn();   
  98TextCol.MappingName = "custID";   
  99TextCol.HeaderText = "序号";   
 100TextCol.Width = 100; 
 101
 102//添加事件处理器   
 103TextCol.TextBox.MouseDown += new MouseEventHandler(TextBoxMouseDownHandler);   
 104TextCol.TextBox.DoubleClick += new EventHandler(TextBoxDoubleClickHandler);   
 105ts1.GridColumnStyles.Add(TextCol); 
 106
 107TextCol = new DataGridTextBoxColumn();   
 108TextCol.MappingName = "custName";   
 109TextCol.HeaderText = "姓名";   
 110TextCol.Width = 100;   
 111//添加事件处理器   
 112TextCol.TextBox.MouseDown += new MouseEventHandler(TextBoxMouseDownHandler);   
 113TextCol.TextBox.DoubleClick += new EventHandler(TextBoxDoubleClickHandler);   
 114ts1.GridColumnStyles.Add(TextCol); 
 115
 116TextCol = new DataGridTextBoxColumn();   
 117TextCol.MappingName = "custCity";   
 118TextCol.HeaderText = "地址";   
 119TextCol.Width = 100;   
 120//添加事件处理器   
 121TextCol.TextBox.MouseDown += new MouseEventHandler(TextBoxMouseDownHandler);   
 122TextCol.TextBox.DoubleClick += new EventHandler(TextBoxDoubleClickHandler);   
 123ts1.GridColumnStyles.Add(TextCol);   
 124  
 125dataGrid1.TableStyles.Add(ts1);   
 126  
 127} 
 128
 129protected override void Dispose( bool disposing )   
 130{   
 131if( disposing )   
 132{   
 133if (components != null)   
 134{   
 135components.Dispose();   
 136}   
 137}   
 138base.Dispose( disposing );   
 139} 
 140
 141#region Windows Form Designer generated code   
 142private void InitializeComponent()   
 143{   
 144this.dataGrid1 = new System.Windows.Forms.DataGrid();   
 145this.label1 = new System.Windows.Forms.Label();   
 146((System.ComponentModel.ISupportInitialize)(this.dataGrid1)).BeginInit();   
 147this.SuspendLayout();   
 148//   
 149// dataGrid1   
 150//   
 151this.dataGrid1.CaptionBackColor = System.Drawing.SystemColors.Info;   
 152this.dataGrid1.CaptionForeColor = System.Drawing.SystemColors.WindowText;   
 153this.dataGrid1.CaptionVisible = false;   
 154this.dataGrid1.DataMember = "";   
 155this.dataGrid1.HeaderForeColor = System.Drawing.SystemColors.ControlText;   
 156this.dataGrid1.Location = new System.Drawing.Point(11, 9);   
 157this.dataGrid1.Name = "dataGrid1";   
 158this.dataGrid1.Size = new System.Drawing.Size(368, 144);   
 159this.dataGrid1.TabIndex = 0;   
 160this.dataGrid1.MouseDown += new System.Windows.Forms.MouseEventHandler(this.dataGrid1_MouseDown);   
 161//   
 162// label1   
 163//   
 164this.label1.Location = new System.Drawing.Point(4, 166);   
 165this.label1.Name = "label1";   
 166this.label1.Size = new System.Drawing.Size(383, 23);   
 167this.label1.TabIndex = 1;   
 168this.label1.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;   
 169this.label1.Click += new System.EventHandler(this.Form1_Click);   
 170//   
 171// Form1   
 172//   
 173this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);   
 174this.ClientSize = new System.Drawing.Size(387, 201);   
 175this.Controls.AddRange(new System.Windows.Forms.Control[] {   
 176this.label1,   
 177this.dataGrid1});   
 178this.Name = "Form1";   
 179this.Text = "鼠标双击事件的例子";   
 180((System.ComponentModel.ISupportInitialize)(this.dataGrid1)).EndInit();   
 181this.ResumeLayout(false); 
 182
 183}   
 184#endregion 
 185
 186[STAThread]   
 187static void Main()   
 188{   
 189Application.Run(new Form1());   
 190} 
 191
 192private void TextBoxDoubleClickHandler(object sender, EventArgs e)   
 193{   
 194MessageBox.Show("双击事件发生。鼠标双击到的值:"+((TextBox)sender).Text.ToString());   
 195} 
 196
 197private void TextBoxMouseDownHandler(object sender, MouseEventArgs e)   
 198{   
 199if(DateTime.Now &lt; gridMouseDownTime.AddMilliseconds(SystemInformation.DoubleClickTime))   
 200{   
 201MessageBox.Show("双击事件发生。鼠标双击到的值:"+((TextBox)sender).Text.ToString());   
 202}   
 203label1.Text = "TextBox 鼠标按下了。 ";   
 204} 
 205
 206private void dataGrid1_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e)   
 207{   
 208gridMouseDownTime = DateTime.Now;   
 209label1.Text = "DataGrid1 鼠标按下了。 ";   
 210} 
 211
 212private void Form1_Click(object sender, System.EventArgs e)   
 213{   
 214label1.Text="";   
 215}   
 216private void label1_Click(object sender, System.EventArgs e)   
 217{   
 218label1.Text="";   
 219}   
 220} 
 221
 222this.myDataGrid.CurrentCellChanged += new   
 223System.EventHandler(this.myDataGrid_CurrentCellChanged); 
 224
 225/////////////////////// 
 226
 227private void myDataGrid_CurrentCellChanged(object sender,   
 228System.EventArgs e)   
 229{   
 230textBox1.Text = "Col is " + myDataGrid.CurrentCell.ColumnNumber   
 231\+ ", Row is " + myDataGrid.CurrentCell.RowNumber   
 232\+ ", Value is " + myDataGrid[myDataGrid.CurrentCell];   
 233} 
 234
 235  
 236把 dsCustomers1和Customers换成你的   
 237private void dataGrid1_Click(object sender, System.EventArgs e)   
 238{   
 239textBox1.BindingContex[this.dsCustomers1,"Customers"].Position=dataGrid1.BindingContext[this.dsCustomers1.Customers].Position;   
 240} 
 241
 242  
 243datagrid的curserchange事件中 
 244
 245textbox1.text=mydatagrid(mydatagrid.currentcell.rownumber,0)   
 246textbox2.text=mydatagrid(mydatagrid.currentcell.rownumber,1)   
 247........ 
 248
 249以此类推 
 250
 251  
 252textbox控件绑定dataset就行了   
 253textBox1.DataBindings.Add(new Binding("Text", ds, "customers.custName")); 
 254
 255  
 256在DataGrid的TableSytle属性中设datagridTableStyle(MappingName为表名),再在其中按你要的次序加入自定义的DataGridTextBoxColumn(MappingName为字段名).每个DataGridTextBoxColumn可以独立设定宽度,。 
 257
 258在winforms datagrid中 
 259
 2601。如何实现行交替变色 
 261
 2622。如何加入链接(例如在 datagrid里放了订单表 ,想点击行中的任何列 可以弹出一个新的form ,放这个订单的---- 用户信息) 
 263
 2643。如何批量删除datagrid里的信息(用了checkBox 
 265
 266  
 267DataGridTableStyle ts1 = new DataGridTableStyle();   
 268dataGrid1.DataSource = aTable; 
 269
 270// Specify the table from dataset (required step)   
 271ts1.MappingName = "A";   
 272  
 273// Set other properties (optional step)   
 274ts1.AlternatingBackColor = Color.LightBlue;   
 275//ts1.AllowSorting = false;   
 276ts1.BackColor = Color.Cyan;   
 277dataGrid1.TableStyles.Add(ts1);   
 278ts1.GridColumnStyles[0].Width = 200;   
 279ts1.DataGrid.Refresh(); 
 280
 281你的第一個問題我給一個例子給你: 
 282
 283datagrid 的樣式表(DataGridTableStyle)應用...   
 284首先 我們先定一個 datatable 和 一個datarow 
 285
 286Private idtb_temp As New DataTable   
 287Private idrw_row As DataRow 
 288
 289private sub GetDataTable()   
 290idtb_temp.Columns.Add("prdodr_subodr_code") '''定義datatable 的列名 
 291
 292idtb_temp.TableName = "SearchTable"   
 293Dim ldcl_header As Windows.Forms.DataGridTextBoxColumn   
 294Dim ldgts_styles As New Windows.Forms.DataGridTableStyle   
 295ldgts_styles.SelectionForeColor = System.Drawing.Color.Yellow   
 296'''選中行的前景色,即字體顏色   
 297ldgts_styles.SelectionBackColor = System.Drawing.Color.Brown '''選中行的背景色 
 298
 299ldgts_styles.ForeColor = System.Drawing.Color.Coral   
 300''' datagrid 中將要顯示的字的顏色   
 301ldgts_styles.AlternatingBackColor = System.Drawing.Color.Cyan   
 302'''datagrid中奇數行所顯示的顏色   
 303ldgts_styles.BackColor = System.Drawing.Color.Cyan   
 304'''datagrid中偶數行所顯示的顏色 
 305
 306ldgts_styles.AllowSorting = False   
 307'''些樣式表定義datagrid不允許自動排序.. 
 308
 309ldgts_styles.MappingName = "SearchTable" 
 310
 311ldcl_header = New Windows.Forms.DataGridTextBoxColumn   
 312'''實例化一個datagridtextboxcolumn   
 313ldcl_header.MappingName = "prdodr_subodr_code"   
 314'''引用前面定義的 “列名”   
 315ldcl_header.HeaderText = "第一列"   
 316'''datagrid 中顯示的 表列頭 文字   
 317ldcl_header.ReadOnly = True '''些列設定為只讀   
 318ldcl_header.TextBox.BorderStyle = BorderStyle.Fixed3D   
 319ldcl_header.TextBox.ForeColor = System.Drawing.Color.Red 
 320
 321ldgts_styles.GridColumnStyles.Add(ldcl_header) 
 322
 323For i As Integer = 0 To 7   
 324idrw_row = idtb_temp.NewRow   
 325idrw_row.Item("prdodr_subodr_code") = "第" &amp; i &amp; "行"   
 326idtb_temp.Rows.Add(idrw_row) 
 327
 328Next 
 329
 330idtb_temp.DefaultView.AllowNew = False   
 331Me.DataGrid1.TableStyles.Add(ldgts_styles)   
 332Me.DataGrid1.DataSource = idtb_temp   
 333end sub 
 334
 335  
 336第三問題:看我的blog   
 337在datagrid 中使用Checkbox, ComboBxo 和 datetimepicker 
 338
 339http://blog.csdn.net/zwxrain/archive/2005/01/19/258998.aspx 
 340
 341  
 3421.在为DataGrid设置了数据源DataSource后,可添加DataGridTableStyle,然后设置其AlternatingBackColor属性和BackColor属性就是交替行的颜色了 
 343
 344主 题: DataGrid 中间单元格点击触发事件是什么? 
 345
 346private void dataGrid1_MouseUp(object sender, System.Windows.Forms.MouseEventArgs e)   
 347  
 348{   
 349  
 350System.Drawing.Point pt = new Point(e.X, e.Y);   
 351  
 352DataGrid.HitTestInfo hti = dataGrid1.HitTest(pt);   
 353  
 354if(hti.Type == DataGrid.HitTestType.Cell)   
 355  
 356{   
 357  
 358dataGrid1.CurrentCell = new DataGridCell(hti.Row, hti.Column);   
 359  
 360dataGrid1.Select(hti.Row);   
 361  
 362}   
 363  
 364} 
 365
 3661.分页;用属性生成器分页后,上页 下页 和页码的click代码该怎么写? 
 367
 3682.编辑;编辑功能该如何的实现。 
 369
 370自己看msdn,看的没头绪,向各位高手请教点思路。多谢!! 
 371
 372分页:   
 373public void dg_PageIndexChanged(object source, System.Web.UI.WebControls.DataGridPageChangedEventArgs e)   
 374{   
 375MyDataGrid.CurrentPageIndex = e.NewPageIndex;   
 376BindData();   
 377}   
 378编辑:   
 379public void edit(object sender,DataGridCommandEventArgs e)   
 380{   
 381type_dg.EditItemIndex=e.Item.ItemIndex;   
 382BindData();   
 383}   
 384public void update(object sender,DataGridCommandEventArgs e)   
 385{   
 386TextBox id=(TextBox)e.Item.Cells[0].Controls[0];   
 387TextBox name=(TextBox)e.Item.Cells[1].Controls[0];   
 388TextBox num=(TextBox)e.Item.Cells[2].Controls[0];   
 389string update_OleDb="update blog_type set b_type_name='"+name.Text+"',b_type_num='"+num.Text+"' where id='"+id.Text+"'";   
 390OleDbConnection myconn=new OleDbConnection(Application["strconn"].ToString());   
 391myconn.Open();   
 392OleDbCommand update_com=new OleDbCommand(update_OleDb,myconn);   
 393update_com.ExecuteNonQuery(); 
 394
 395type_dg.EditItemIndex=-1;   
 396myconn.Close();   
 397BindData();   
 398} 
 399
 400public void cancel(object sender,DataGridCommandEventArgs e)   
 401{   
 402type_dg.EditItemIndex=-1;   
 403BindData();   
 404} 
 405
 406  
 407删除:   
 408public void delete(object sender,DataGridCommandEventArgs e)   
 409{   
 410string no=type_dg.Items[e.Item.ItemIndex].Cells[0].Text;   
 411OleDbConnection myconn=new OleDbConnection(Application["strconn"].ToString());   
 412myconn.Open();   
 413string deleteOleDb="delete from blog_type where id="+no;   
 414OleDbCommand deletecom=new OleDbCommand(deleteOleDb,myconn);   
 415deletecom.ExecuteNonQuery();   
 416myconn.Close();   
 417BindData();   
 418} 
 419
 420在winform的dataGrid中如何更改列的标题和设置列内容。 
 421
 422  
 423表:   
 424id name strdate enddate   
 4251 a 2004/2/1 2005/2/1 
 426
 427要求显示出来   
 428名称 开始日期 结束日期 逾期(是/否)   
 429a 2004/2/1 2005/2/1 逾期365天   
 430谢谢! 
 431
 432  
 433private void Form1_Load(object sender, System.EventArgs e)   
 434{   
 435SqlConnection CS = new SqlConnection("server=mengxianhui;database=SqlPUB2;User Id=sa;password=");   
 436SqlDataAdapter myCommand = new SqlDataAdapter("Select lastmodified,objectId from BaseObject", CS);   
 437DataSet myDataSet = new DataSet();   
 438myCommand.Fill(myDataSet, "BaseObject");   
 439this.dataGrid1.DataSource = myDataSet.Tables[0];   
 440//设置DataGrid的各列   
 441DataGridTextBoxColumn c1=new DataGridTextBoxColumn();   
 442DataGridTextBoxColumn c2=new DataGridTextBoxColumn(); 
 443
 444c1.MappingName = "lastmodified";   
 445c2.MappingName = "objectId"; 
 446
 447c1.HeaderText="时间【你好,夏威夷】";   
 448c2.HeaderText="标号";   
 449c1.Format="yyyy年MM月dd日";   
 450c1.Width = 200; 
 451
 452DataGridTableStyle dts=new DataGridTableStyle();   
 453dts.GridColumnStyles.Add(c1);   
 454dts.GridColumnStyles.Add(c2);   
 455dts.MappingName="BaseObject";   
 456this.dataGrid1.TableStyles.Add(dts);   
 457} 
 458
 459主 题: DataGrid+CheckBoxList应用问题 
 460
 461你可以添加一个模板列,然后对模板列进行编辑,加入一个CheckBox和一个CheckBoxList,然后命名这两个控件,在CODE加入CheckBox1_CheckedChanged事件,把CheckBox的Auto PostBack设置为true,再在   
 462CheckBox1_CheckedChanged事件写你所要实现的功能。 
 463
 464  
 465下面是一个简单例子,删除DataGrid当前行数据:(前面数据已经绑定到dataGrid1了) 
 466
 467string strSQL = "DELETE FROM Table1 WHERE Id=@Id ";   
 468string text = dataGrid1[dataGrid1.CurrentCell.RowNumber, 0].ToString();   
 469testDataSet1.Table1.Rows[dataGrid1.CurrentCell.RowNumber].Delete();   
 470testDataSet1.AcceptChanges();   
 471sqlDataAdapter2.DeleteCommand.Parameters["@Id"].Value = text;   
 472sqlDataAdapter2.DeleteCommand.Connection.Open();   
 473sqlDataAdapter2.DeleteCommand.ExecuteNonQuery();   
 474sqlDataAdapter2.DeleteCommand.Connection.Close(); 
 475
 476  
 477主 题: 请教在DataGridView中怎样生成自适应的列宽? 
 478
 479自适应 列宽: 
 480
 481'控制dategrid列宽度函数   
 482Public Sub SizeColumnsToContent(ByVal dataGrid As DataGrid, ByVal nRowsToScan As Integer)   
 483Dim Graphics As Graphics = dataGrid.CreateGraphics()   
 484Dim tableStyle As DataGridTableStyle = New DataGridTableStyle 
 485
 486Try 
 487
 488Dim dataTable As DataTable = CType(dataGrid.DataSource, DataTable) 
 489
 490If -1 = nRowsToScan Then 
 491
 492nRowsToScan = dataTable.Rows.Count 
 493
 494Else   
 495nRowsToScan = System.Math.Min(nRowsToScan, dataTable.Rows.Count)   
 496End If 
 497
 498dataGrid.TableStyles.Clear()   
 499tableStyle.MappingName = dataTable.TableName   
 500Dim columnStyle As DataGridTextBoxColumn   
 501Dim iWidth As Integer   
 502For iCurrCol As Integer = 0 To dataTable.Columns.Count - 1   
 503Dim dataColumn As DataColumn = dataTable.Columns(iCurrCol)   
 504columnStyle = New DataGridTextBoxColumn   
 505columnStyle.TextBox.Enabled = True   
 506columnStyle.HeaderText = dataColumn.ColumnName   
 507columnStyle.MappingName = dataColumn.ColumnName   
 508iWidth = CInt(Graphics.MeasureString(columnStyle.HeaderText, dataGrid.Font).Width)   
 509Dim dataRow As DataRow   
 510For iRow As Integer = 0 To nRowsToScan - 1   
 511dataRow = dataTable.Rows(iRow)   
 512If dataRow(dataColumn.ColumnName) &lt;&gt; Nothing Then   
 513Dim iColWidth As Integer = CInt(Graphics.MeasureString(dataRow.ItemArray(iCurrCol).ToString(), dataGrid.Font).Width)   
 514Dim iColHight As Integer = CInt(Graphics.MeasureString(dataRow.ItemArray(iCurrCol).ToString(), dataGrid.Font).Height)   
 515iWidth = CInt(System.Math.Max(iWidth, iColWidth))   
 516End If   
 517Next   
 518columnStyle.Width = iWidth + 10   
 519tableStyle.GridColumnStyles.Add(columnStyle)   
 520Next   
 521dataGrid.TableStyles.Add(tableStyle)   
 522Catch ex As Exception   
 523MessageBox.Show(ex.Message)   
 524Finally   
 525Graphics.Dispose()   
 526End Try   
 527End Sub 
 528
 529  
 530主 题: WinForm中隐藏Datagrid中的一列,有简单的方法吗?   
 531我也是用DataGrid.TableStyles[Table].GridColumnStyles[0].Width = 0;这么做的.应该是没有其他的方法了 
 532
 533主 题: WinForm里面怎么捕获DataGrid的双击事件阿? 
 534
 535  
 536namespace DataGridDoubleClick   
 537{   
 538using System;   
 539using System.Drawing;   
 540using System.Collections;   
 541using System.ComponentModel;   
 542using System.Windows.Forms;   
 543using System.Data; 
 544
 545public class Form1 : System.Windows.Forms.Form   
 546{   
 547private System.Windows.Forms.DataGrid dataGrid1;   
 548private DataSet myDataSet;   
 549DateTime gridMouseDownTime;   
 550private System.Windows.Forms.Label label1;   
 551  
 552private System.ComponentModel.Container components = null; 
 553
 554public Form1()   
 555{   
 556InitializeComponent();   
 557gridMouseDownTime = DateTime.Now;   
 558SetUp();   
 559} 
 560
 561private void SetUp()   
 562{   
 563// 用2个Table和1和Relation创建DataSet   
 564MakeDataSet();   
 565// 数据绑定   
 566dataGrid1.SetDataBinding(myDataSet, "Customers"); 
 567
 568//添加样式   
 569AddCustomDataTableStyle();   
 570} 
 571
 572private void MakeDataSet()   
 573{   
 574// 创建DataSet.   
 575myDataSet = new DataSet("myDataSet");   
 576  
 577// 创建2个DataTables.   
 578DataTable tCust = new DataTable("Customers");   
 579  
 580// 创建两个列,并添加到第一个表   
 581DataColumn cCustID = new DataColumn("custID");   
 582DataColumn cCustName = new DataColumn("custName");   
 583DataColumn cCurrent = new DataColumn("custCity");   
 584tCust.Columns.Add(cCustID);   
 585tCust.Columns.Add(cCustName);   
 586tCust.Columns.Add(cCurrent); 
 587
 588// 把tables添加到DataSet.   
 589myDataSet.Tables.Add(tCust);   
 590  
 591  
 592/* 计算tables.对每个客户,创建DataRow变量 */   
 593DataRow newRow1;   
 594  
 595// 添加记录到 Customers Table.   
 596for(int i = 1; i &lt; 4; i++)   
 597{   
 598newRow1 = tCust.NewRow();   
 599newRow1["custID"] = (100*i).ToString();   
 600tCust.Rows.Add(newRow1);   
 601} 
 602
 603tCust.Rows[0]["custName"] = "【孟宪会之精彩世界】";   
 604tCust.Rows[1]["custName"] = "net_lover";   
 605tCust.Rows[2]["custName"] = " http://xml.sz.luohuedu.net/ "; 
 606
 607  
 608tCust.Rows[0]["custCity"] = "北京";   
 609tCust.Rows[1]["custCity"] = "上海";   
 610tCust.Rows[2]["custCity"] = "河南";   
 611} 
 612
 613private void AddCustomDataTableStyle()   
 614{   
 615DataGridTableStyle ts1 = new DataGridTableStyle();   
 616ts1.MappingName = "Customers";   
 617// 设置属性   
 618ts1.AlternatingBackColor = Color.LightGray; 
 619
 620// 添加Textbox列样式,以便我们捕捉鼠标事件   
 621DataGridTextBoxColumn TextCol = new DataGridTextBoxColumn();   
 622TextCol.MappingName = "custID";   
 623TextCol.HeaderText = "序号";   
 624TextCol.Width = 100; 
 625
 626//添加事件处理器   
 627TextCol.TextBox.MouseDown += new MouseEventHandler(TextBoxMouseDownHandler);   
 628TextCol.TextBox.DoubleClick += new EventHandler(TextBoxDoubleClickHandler);   
 629ts1.GridColumnStyles.Add(TextCol); 
 630
 631TextCol = new DataGridTextBoxColumn();   
 632TextCol.MappingName = "custName";   
 633TextCol.HeaderText = "姓名";   
 634TextCol.Width = 100;   
 635//添加事件处理器   
 636TextCol.TextBox.MouseDown += new MouseEventHandler(TextBoxMouseDownHandler);   
 637TextCol.TextBox.DoubleClick += new EventHandler(TextBoxDoubleClickHandler);   
 638ts1.GridColumnStyles.Add(TextCol); 
 639
 640TextCol = new DataGridTextBoxColumn();   
 641TextCol.MappingName = "custCity";   
 642TextCol.HeaderText = "地址";   
 643TextCol.Width = 100;   
 644//添加事件处理器   
 645TextCol.TextBox.MouseDown += new MouseEventHandler(TextBoxMouseDownHandler);   
 646TextCol.TextBox.DoubleClick += new EventHandler(TextBoxDoubleClickHandler);   
 647ts1.GridColumnStyles.Add(TextCol);   
 648  
 649dataGrid1.TableStyles.Add(ts1);   
 650  
 651} 
 652
 653protected override void Dispose( bool disposing )   
 654{   
 655if( disposing )   
 656{   
 657if (components != null)   
 658{   
 659components.Dispose();   
 660}   
 661}   
 662base.Dispose( disposing );   
 663} 
 664
 665#region Windows Form Designer generated code   
 666private void InitializeComponent()   
 667{   
 668this.dataGrid1 = new System.Windows.Forms.DataGrid();   
 669this.label1 = new System.Windows.Forms.Label();   
 670((System.ComponentModel.ISupportInitialize)(this.dataGrid1)).BeginInit();   
 671this.SuspendLayout();   
 672//   
 673// dataGrid1   
 674//   
 675this.dataGrid1.CaptionBackColor = System.Drawing.SystemColors.Info;   
 676this.dataGrid1.CaptionForeColor = System.Drawing.SystemColors.WindowText;   
 677this.dataGrid1.CaptionVisible = false;   
 678this.dataGrid1.DataMember = "";   
 679this.dataGrid1.HeaderForeColor = System.Drawing.SystemColors.ControlText;   
 680this.dataGrid1.Location = new System.Drawing.Point(11, 9);   
 681this.dataGrid1.Name = "dataGrid1";   
 682this.dataGrid1.Size = new System.Drawing.Size(368, 144);   
 683this.dataGrid1.TabIndex = 0;   
 684this.dataGrid1.MouseDown += new System.Windows.Forms.MouseEventHandler(this.dataGrid1_MouseDown);   
 685//   
 686// label1   
 687//   
 688this.label1.Location = new System.Drawing.Point(4, 166);   
 689this.label1.Name = "label1";   
 690this.label1.Size = new System.Drawing.Size(383, 23);   
 691this.label1.TabIndex = 1;   
 692this.label1.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;   
 693this.label1.Click += new System.EventHandler(this.Form1_Click);   
 694//   
 695// Form1   
 696//   
 697this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);   
 698this.ClientSize = new System.Drawing.Size(387, 201);   
 699this.Controls.AddRange(new System.Windows.Forms.Control[] {   
 700this.label1,   
 701this.dataGrid1});   
 702this.Name = "Form1";   
 703this.Text = "鼠标双击事件的例子";   
 704((System.ComponentModel.ISupportInitialize)(this.dataGrid1)).EndInit();   
 705this.ResumeLayout(false); 
 706
 707}   
 708#endregion 
 709
 710[STAThread]   
 711static void Main()   
 712{   
 713Application.Run(new Form1());   
 714} 
 715
 716private void TextBoxDoubleClickHandler(object sender, EventArgs e)   
 717{   
 718MessageBox.Show("双击事件发生。鼠标双击到的值:"+((TextBox)sender).Text.ToString());   
 719} 
 720
 721private void TextBoxMouseDownHandler(object sender, MouseEventArgs e)   
 722{   
 723if(DateTime.Now &lt; gridMouseDownTime.AddMilliseconds(SystemInformation.DoubleClickTime))   
 724{   
 725MessageBox.Show("双击事件发生。鼠标双击到的值:"+((TextBox)sender).Text.ToString());   
 726}   
 727label1.Text = "TextBox 鼠标按下了。 ";   
 728} 
 729
 730private void dataGrid1_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e)   
 731{   
 732gridMouseDownTime = DateTime.Now;   
 733label1.Text = "DataGrid1 鼠标按下了。 ";   
 734} 
 735
 736private void Form1_Click(object sender, System.EventArgs e)   
 737{   
 738label1.Text="";   
 739}   
 740private void label1_Click(object sender, System.EventArgs e)   
 741{   
 742label1.Text="";   
 743}   
 744}   
 745} 
 746
 747  
 748namespace DataGridDoubleClick   
 749{   
 750using System;   
 751using System.Drawing;   
 752using System.Collections;   
 753using System.ComponentModel;   
 754using System.Windows.Forms;   
 755using System.Data; 
 756
 757public class Form1 : System.Windows.Forms.Form   
 758{   
 759private System.Windows.Forms.DataGrid dataGrid1;   
 760private DataSet myDataSet;   
 761DateTime gridMouseDownTime;   
 762private System.Windows.Forms.Label label1;   
 763  
 764private System.ComponentModel.Container components = null; 
 765
 766public Form1()   
 767{   
 768InitializeComponent();   
 769gridMouseDownTime = DateTime.Now;   
 770SetUp();   
 771} 
 772
 773private void SetUp()   
 774{   
 775// 用2个Table和1和Relation创建DataSet   
 776MakeDataSet();   
 777// 数据绑定   
 778dataGrid1.SetDataBinding(myDataSet, "Customers"); 
 779
 780//添加样式   
 781AddCustomDataTableStyle();   
 782} 
 783
 784private void MakeDataSet()   
 785{   
 786// 创建DataSet.   
 787myDataSet = new DataSet("myDataSet");   
 788  
 789// 创建2个DataTables.   
 790DataTable tCust = new DataTable("Customers");   
 791  
 792// 创建两个列,并添加到第一个表   
 793DataColumn cCustID = new DataColumn("custID");   
 794DataColumn cCustName = new DataColumn("custName");   
 795DataColumn cCurrent = new DataColumn("custCity");   
 796tCust.Columns.Add(cCustID);   
 797tCust.Columns.Add(cCustName);   
 798tCust.Columns.Add(cCurrent); 
 799
 800// 把tables添加到DataSet.   
 801myDataSet.Tables.Add(tCust);   
 802  
 803  
 804/* 计算tables.对每个客户,创建DataRow变量 */   
 805DataRow newRow1;   
 806  
 807// 添加记录到 Customers Table.   
 808for(int i = 1; i &lt; 4; i++)   
 809{   
 810newRow1 = tCust.NewRow();   
 811newRow1["custID"] = (100*i).ToString();   
 812tCust.Rows.Add(newRow1);   
 813} 
 814
 815tCust.Rows[0]["custName"] = "【孟宪会之精彩世界】";   
 816tCust.Rows[1]["custName"] = "net_lover";   
 817tCust.Rows[2]["custName"] = " http://xml.sz.luohuedu.net/ "; 
 818
 819  
 820tCust.Rows[0]["custCity"] = "北京";   
 821tCust.Rows[1]["custCity"] = "上海";   
 822tCust.Rows[2]["custCity"] = "河南";   
 823} 
 824
 825private void AddCustomDataTableStyle()   
 826{   
 827DataGridTableStyle ts1 = new DataGridTableStyle();   
 828ts1.MappingName = "Customers";   
 829// 设置属性   
 830ts1.AlternatingBackColor = Color.LightGray; 
 831
 832// 添加Textbox列样式,以便我们捕捉鼠标事件   
 833DataGridTextBoxColumn TextCol = new DataGridTextBoxColumn();   
 834TextCol.MappingName = "custID";   
 835TextCol.HeaderText = "序号";   
 836TextCol.Width = 100; 
 837
 838//添加事件处理器   
 839TextCol.TextBox.MouseDown += new MouseEventHandler(TextBoxMouseDownHandler);   
 840TextCol.TextBox.DoubleClick += new EventHandler(TextBoxDoubleClickHandler);   
 841ts1.GridColumnStyles.Add(TextCol); 
 842
 843TextCol = new DataGridTextBoxColumn();   
 844TextCol.MappingName = "custName";   
 845TextCol.HeaderText = "姓名";   
 846TextCol.Width = 100;   
 847//添加事件处理器   
 848TextCol.TextBox.MouseDown += new MouseEventHandler(TextBoxMouseDownHandler);   
 849TextCol.TextBox.DoubleClick += new EventHandler(TextBoxDoubleClickHandler);   
 850ts1.GridColumnStyles.Add(TextCol); 
 851
 852TextCol = new DataGridTextBoxColumn();   
 853TextCol.MappingName = "custCity";   
 854TextCol.HeaderText = "地址";   
 855TextCol.Width = 100;   
 856//添加事件处理器   
 857TextCol.TextBox.MouseDown += new MouseEventHandler(TextBoxMouseDownHandler);   
 858TextCol.TextBox.DoubleClick += new EventHandler(TextBoxDoubleClickHandler);   
 859ts1.GridColumnStyles.Add(TextCol);   
 860  
 861dataGrid1.TableStyles.Add(ts1);   
 862  
 863} 
 864
 865protected override void Dispose( bool disposing )   
 866{   
 867if( disposing )   
 868{   
 869if (components != null)   
 870{   
 871components.Dispose();   
 872}   
 873}   
 874base.Dispose( disposing );   
 875} 
 876
 877#region Windows Form Designer generated code   
 878private void InitializeComponent()   
 879{   
 880this.dataGrid1 = new System.Windows.Forms.DataGrid();   
 881this.label1 = new System.Windows.Forms.Label();   
 882((System.ComponentModel.ISupportInitialize)(this.dataGrid1)).BeginInit();   
 883this.SuspendLayout();   
 884//   
 885// dataGrid1   
 886//   
 887this.dataGrid1.CaptionBackColor = System.Drawing.SystemColors.Info;   
 888this.dataGrid1.CaptionForeColor = System.Drawing.SystemColors.WindowText;   
 889this.dataGrid1.CaptionVisible = false;   
 890this.dataGrid1.DataMember = "";   
 891this.dataGrid1.HeaderForeColor = System.Drawing.SystemColors.ControlText;   
 892this.dataGrid1.Location = new System.Drawing.Point(11, 9);   
 893this.dataGrid1.Name = "dataGrid1";   
 894this.dataGrid1.Size = new System.Drawing.Size(368, 144);   
 895this.dataGrid1.TabIndex = 0;   
 896this.dataGrid1.MouseDown += new System.Windows.Forms.MouseEventHandler(this.dataGrid1_MouseDown);   
 897//   
 898// label1   
 899//   
 900this.label1.Location = new System.Drawing.Point(4, 166);   
 901this.label1.Name = "label1";   
 902this.label1.Size = new System.Drawing.Size(383, 23);   
 903this.label1.TabIndex = 1;   
 904this.label1.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;   
 905this.label1.Click += new System.EventHandler(this.Form1_Click);   
 906//   
 907// Form1   
 908//   
 909this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);   
 910this.ClientSize = new System.Drawing.Size(387, 201);   
 911this.Controls.AddRange(new System.Windows.Forms.Control[] {   
 912this.label1,   
 913this.dataGrid1});   
 914this.Name = "Form1";   
 915this.Text = "鼠标双击事件的例子";   
 916((System.ComponentModel.ISupportInitialize)(this.dataGrid1)).EndInit();   
 917this.ResumeLayout(false); 
 918
 919}   
 920#endregion 
 921
 922[STAThread]   
 923static void Main()   
 924{   
 925Application.Run(new Form1());   
 926} 
 927
 928private void TextBoxDoubleClickHandler(object sender, EventArgs e)   
 929{   
 930MessageBox.Show("双击事件发生。鼠标双击到的值:"+((TextBox)sender).Text.ToString());   
 931} 
 932
 933private void TextBoxMouseDownHandler(object sender, MouseEventArgs e)   
 934{   
 935if(DateTime.Now &lt; gridMouseDownTime.AddMilliseconds(SystemInformation.DoubleClickTime))   
 936{   
 937MessageBox.Show("双击事件发生。鼠标双击到的值:"+((TextBox)sender).Text.ToString());   
 938}   
 939label1.Text = "TextBox 鼠标按下了。 ";   
 940} 
 941
 942private void dataGrid1_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e)   
 943{   
 944gridMouseDownTime = DateTime.Now;   
 945label1.Text = "DataGrid1 鼠标按下了。 ";   
 946} 
 947
 948private void Form1_Click(object sender, System.EventArgs e)   
 949{   
 950label1.Text="";   
 951}   
 952private void label1_Click(object sender, System.EventArgs e)   
 953{   
 954label1.Text="";   
 955}   
 956}   
 957} 
 958
 959主 题: 在C#(winform)中如何设置datagrid某一行的背景色,或字体的颜色啊?高手救命!! 
 960
 961  
 962using System;   
 963using System.Drawing;   
 964using System.Collections;   
 965using System.ComponentModel;   
 966using System.Windows.Forms;   
 967using System.Data; 
 968
 969namespace DataGridCellFormatting   
 970{   
 971/// <summary>   
 972/// Form2 的摘要说明。   
 973/// </summary>   
 974public class Form2 : System.Windows.Forms.Form   
 975{   
 976private System.Windows.Forms.DataGrid dataGrid1;   
 977/// <summary>   
 978/// 必需的设计器变量。   
 979/// </summary>   
 980private System.ComponentModel.Container components = null; 
 981
 982public Form2()   
 983{   
 984//   
 985// Windows 窗体设计器支持所必需的   
 986//   
 987InitializeComponent(); 
 988
 989//   
 990// TODO: 在 InitializeComponent 调用后添加任何构造函数代码   
 991//   
 992} 
 993
 994/// <summary>   
 995/// 清理所有正在使用的资源。   
 996/// </summary>   
 997protected override void Dispose( bool disposing )   
 998{   
 999if( disposing )   
1000{   
1001if(components != null)   
1002{   
1003components.Dispose();   
1004}   
1005}   
1006base.Dispose( disposing );   
1007} 
1008
1009#region Windows 窗体设计器生成的代码   
1010/// <summary>   
1011/// 设计器支持所需的方法 - 不要使用代码编辑器修改   
1012/// 此方法的内容。   
1013/// </summary>   
1014private void InitializeComponent()   
1015{   
1016this.dataGrid1 = new System.Windows.Forms.DataGrid();   
1017((System.ComponentModel.ISupportInitialize)(this.dataGrid1)).BeginInit();   
1018this.SuspendLayout();   
1019//   
1020// dataGrid1   
1021//   
1022this.dataGrid1.DataMember = "";   
1023this.dataGrid1.HeaderForeColor = System.Drawing.SystemColors.ControlText;   
1024this.dataGrid1.Location = new System.Drawing.Point(8, 56);   
1025this.dataGrid1.Name = "dataGrid1";   
1026this.dataGrid1.Size = new System.Drawing.Size(536, 296);   
1027this.dataGrid1.TabIndex = 0;   
1028this.dataGrid1.Navigate += new System.Windows.Forms.NavigateEventHandler(this.dataGrid1_Navigate);   
1029//   
1030// Form2   
1031//   
1032this.AutoScaleBaseSize = new System.Drawing.Size(6, 14);   
1033this.ClientSize = new System.Drawing.Size(560, 389);   
1034this.Controls.Add(this.dataGrid1);   
1035this.Name = "Form2";   
1036this.Text = "Form2";   
1037this.Load += new System.EventHandler(this.Form2_Load);   
1038((System.ComponentModel.ISupportInitialize)(this.dataGrid1)).EndInit();   
1039this.ResumeLayout(false); 
1040
1041}   
1042#endregion 
1043
1044  
1045private void FormatGridCells(object sender, DataGridFormatCellEventArgs e)   
1046{   
1047//color row 1 red   
1048if(e.Row == 0)   
1049e.BackBrush = Brushes.Red;   
1050if(e.Row == 1)   
1051e.BackBrush = Brushes.Red;   
1052if(e.Row == 2)   
1053e.BackBrush = Brushes.Red;   
1054if(e.Row == 3)   
1055e.BackBrush = Brushes.Red; 
1056
1057//color column 4 blue   
1058//if(e.Column == 4)   
1059//e.BackBrush = Brushes.Blue;   
1060//   
1061////set font of some cells to bold   
1062//if( (e.Row + e.Column) % 5 == 0 )   
1063//e.TextFont = new Font(e.TextFont.Name, e.TextFont.Size, FontStyle.Bold);   
1064//   
1065////set textcolor of some cells to blue   
1066//if( (e.Row + e.Column) % 8 == 0 )   
1067//e.ForeBrush = Brushes.DodgerBlue;   
1068//   
1069////set font of some cells to bold, underline, italic with white text on green background   
1070//if( (e.Row + e.Column) % 9 == 0 )   
1071//{   
1072//e.TextFont = new Font(e.TextFont.Name, e.TextFont.Size, FontStyle.Bold | FontStyle.Italic | FontStyle.Underline);   
1073//e.ForeBrush = Brushes.White;   
1074//e.BackBrush = Brushes.Green;   
1075//} 
1076
1077  
1078} 
1079
1080private DataTable SomeDataTable()   
1081{   
1082DataTable dt = new DataTable("MyTable"); 
1083
1084//add some columns   
1085int nCols = 10;   
1086for(int j = 0; j &lt; nCols; ++j)   
1087dt.Columns.Add(new DataColumn(string.Format("col{0}", j), typeof(string))); 
1088
1089//add some rows   
1090int nRows = 40;   
1091for(int i = 0; i &lt; nRows; ++i)   
1092{   
1093DataRow dr = dt.NewRow();   
1094for(int j = 0; j &lt; nCols; ++j)   
1095dr[j] = string.Format("row {0} col {1}", i, j);   
1096dt.Rows.Add(dr);   
1097} 
1098
1099dt.DefaultView.AllowNew = false;//turn off append row   
1100return dt;   
1101} 
1102
1103private void AddCellFormattingColumnStyles(DataGrid grid, FormatCellEventHandler handler)   
1104{   
1105DataGridTableStyle ts = new DataGridTableStyle(); 
1106
1107DataTable dt = (DataTable) grid.DataSource; 
1108
1109ts.MappingName = dt.TableName; 
1110
1111for(int j = 0; j &lt; dt.Columns.Count; ++j)   
1112{   
1113DataGridFormattableTextBoxColumn cs = new DataGridFormattableTextBoxColumn(j);   
1114cs.MappingName = dt.Columns[j].ColumnName;   
1115cs.HeaderText = dt.Columns[j].ColumnName;   
1116cs.SetCellFormat += handler;   
1117ts.GridColumnStyles.Add(cs);   
1118} 
1119
1120grid.TableStyles.Clear();   
1121grid.TableStyles.Add(ts); 
1122
1123}   
1124private void dataGrid1_Navigate(object sender, System.Windows.Forms.NavigateEventArgs ne)   
1125{ 
1126
1127} 
1128
1129private void Form2_Load(object sender, System.EventArgs e)   
1130{   
1131this.dataGrid1.DataSource = SomeDataTable(); 
1132
1133AddCellFormattingColumnStyles(this.dataGrid1, new FormatCellEventHandler(FormatGridCells));   
1134} 
1135
1136public delegate void FormatCellEventHandler(object sender, DataGridFormatCellEventArgs e); 
1137
1138public class DataGridFormatCellEventArgs : EventArgs   
1139{   
1140private int _column;   
1141private int _row;   
1142private Font _font;   
1143private Brush _backBrush;   
1144private Brush _foreBrush;   
1145private bool _useBaseClassDrawing; 
1146
1147  
1148public DataGridFormatCellEventArgs(int row, int col, Font font1, Brush backBrush, Brush foreBrush)   
1149{   
1150_row = row;   
1151_column = col;   
1152_font = font1;   
1153_backBrush = backBrush;   
1154_foreBrush = foreBrush;   
1155_useBaseClassDrawing = false;   
1156} 
1157
1158public int Column   
1159{   
1160get{ return _column;}   
1161set{ _column = value;}   
1162}   
1163public int Row   
1164{   
1165get{ return _row;}   
1166set{ _row = value;}   
1167}   
1168public Font TextFont   
1169{   
1170get{ return _font;}   
1171set{ _font = value;}   
1172} 
1173
1174public Brush BackBrush   
1175{   
1176get{ return _backBrush;}   
1177set{ _backBrush = value;}   
1178}   
1179public Brush ForeBrush   
1180{   
1181get{ return _foreBrush;}   
1182set{ _foreBrush = value;}   
1183}   
1184public bool UseBaseClassDrawing   
1185{   
1186get{ return _useBaseClassDrawing;}   
1187set{ _useBaseClassDrawing = value;}   
1188}   
1189} 
1190
1191public class DataGridFormattableTextBoxColumn : DataGridTextBoxColumn   
1192{   
1193//in your handler, set the EnableValue to true or false, depending upon the row &amp; col   
1194public event FormatCellEventHandler SetCellFormat; 
1195
1196private int _col; 
1197
1198public DataGridFormattableTextBoxColumn(int col)   
1199{   
1200_col = col;   
1201} 
1202
1203protected override void Paint(System.Drawing.Graphics g, System.Drawing.Rectangle bounds, System.Windows.Forms.CurrencyManager source, int rowNum, System.Drawing.Brush backBrush, System.Drawing.Brush foreBrush, bool alignToRight)   
1204{   
1205DataGridFormatCellEventArgs e = new DataGridFormatCellEventArgs(rowNum, this._col, this.DataGridTableStyle.DataGrid.Font, backBrush, foreBrush);   
1206if(SetCellFormat != null)   
1207{   
1208SetCellFormat(this, e);   
1209}   
1210if(e.UseBaseClassDrawing)   
1211base.Paint(g, bounds, source, rowNum, backBrush, foreBrush, alignToRight);   
1212else   
1213{   
1214g.FillRectangle(e.BackBrush, bounds);   
1215g.DrawString(this.GetColumnValueAtRow(source, rowNum).ToString(), e.TextFont, e.ForeBrush, bounds.X, bounds.Y);   
1216}   
1217if(e.TextFont != this.DataGridTableStyle.DataGrid.Font)   
1218e.TextFont.Dispose();   
1219} 
1220
1221protected override void Edit(System.Windows.Forms.CurrencyManager source, int rowNum, System.Drawing.Rectangle bounds, bool readOnly, string instantText, bool cellIsVisible)   
1222{   
1223//comment to make cells unable to become editable   
1224base.Edit(source, rowNum, bounds, readOnly, instantText, cellIsVisible);   
1225} 
1226
1227}   
1228}   
1229} 
1230
1231  
1232只需要改变FormatGridCells中的行就行了 
1233
1234主 题: 如何让WINFORM的DATAGRID控件的列有的为只读属性,有的不是只读属性 
1235
12361、手工:Datagrid-&gt;属性-&gt;TableStyles-&gt;GridCoumnStyles 
1237
12382、代码:this.dataGrid1.TableStyles["tablename"].GridColumnStyles["ID"].ReadOnly = true; 
1239
1240  
1241this.dataGrid1.TableStyles["tablename"].GridColumnStyles["ID"].ReadOnly = true; 
1242
1243显示和隐藏DataGrid中的列 

@ Page Language="vb" AutoEventWireup="false" Codebehind="ShowHideCols.aspx.vb"
Inherits="aspxWeb.ShowHideCols"

 1<!DOCTYPE html PUBLIC "-//W3C//DTD html 4.0 Transitional//EN">
 2
 3<html>
 4<head>
 5<title>ShowHideCols</title>
 6<meta content="Microsoft Visual Studio.NET 7.0" name="GENERATOR"/>
 7<meta content="Visual Basic 7.0" name="CODE_LANGUAGE"/>
 8<meta content="JavaScript" name="vs_defaultClientScript"/>
 9<meta content=" http://schemas.microsoft.com/intellisense/ie5 " name="vs_targetSchema"/>
10</head>
11<body ms_positioning="GridLayout">
12<form id="Form1" method="post" runat="server">
13<asp:button id="btnShow" onclick="ShowDetails" runat="server" text="Show Details"></asp:button>
14<asp:button id="btnHide" onclick="HideDetails" runat="server" text="Hide Details"></asp:button>
15<asp:datagrid autogeneratecolumns="False" backcolor="White" bordercolor="#999999" borderstyle="None" borderwidth="1px" cellpadding="3" gridlines="Vertical" id="dtgCusts" runat="server">
16<columns>
17<asp:boundcolumn datafield="Title"></asp:boundcolumn>
18<asp:boundcolumn datafield="id" visible="False"></asp:boundcolumn>
19<asp:boundcolumn datafield="CreateDate" dataformatstring="{0:yyyy-MM-dd HH:mm:ss}" visible="False"></asp:boundcolumn>
20<asp:editcommandcolumn edittext="Edit" headertext="Edit" visible="False"></asp:editcommandcolumn>
21</columns>
22<alternatingitemstyle backcolor="#DCDCDC"></alternatingitemstyle>
23<itemstyle backcolor="#EEEEEE" forecolor="Black"></itemstyle>
24<headerstyle backcolor="#000084" font-bold="True" forecolor="White"></headerstyle>
25</asp:datagrid>
26</form>
27</body>
28</html>
29
30Imports System.Data   
31Imports System.Data.OleDb 
32
33Public Class ShowHideCols   
34Inherits System.Web.UI.Page   
35Protected WithEvents btnShow As System.Web.UI.WebControls.Button   
36Protected WithEvents btnHide As System.Web.UI.WebControls.Button   
37Protected WithEvents dtgCusts As System.Web.UI.WebControls.DataGrid 
38
39#Region " Web 窗体设计器生成的代码 " 
40
41'该调用是 Web 窗体设计器所必需的。   
42<system.diagnostics.debuggerstepthrough()> Private Sub InitializeComponent() 
43
44End Sub 
45
46Private Sub Page_Init(ByVal sender As System.Object, ByVal e As System.EventArgs)_   
47Handles MyBase.Init   
48'CODEGEN: 此方法调用是 Web 窗体设计器所必需的   
49'不要使用代码编辑器修改它。   
50InitializeComponent()   
51End Sub 
52
53#End Region 
54
55Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs)_   
56Handles MyBase.Load   
57'在此处放置初始化页的用户代码   
58btnShow.Text = "显示列"   
59btnHide.Text = "隐藏列"   
60dtgCusts.Columns(1).HeaderText = ""   
61dtgCusts.Columns(0).HeaderText = "标题"   
62dtgCusts.Columns(2).HeaderText = "发布日期"   
63dtgCusts.Columns(3).HeaderText = "编辑"   
64If Not IsPostBack Then   
65BindTheData()   
66End If   
67End Sub 
68
69Sub BindTheData()   
70n</system.diagnostics.debuggerstepthrough()></asp:boundcolumn>
Published At
Categories with Web编程
Tagged with
comments powered by Disqus