`

DataGridView使用技巧(集)

 
阅读更多

一、DataGridView 单元格验证

1、定义单元格验证
要求:
验证错误后焦点不离开。
实现:
单元格的验证可以使用dgv_details_CellValidating事件。
验证不通过时调用e.Cancel = true;终止事件链,单元格将保持编辑状态。
调用dgv_details.CancelEdit();可以使单元格的内容会滚到修改前的值。
使用System.Windows.Forms.SendKeys.Send("^a");将全选单元格的内容。

2、单元格选中并开始编辑状态
实现:

  1. //DataGridView获得焦点
  2. dgv_details.Focus();
  3. //DataGridView指定当前单元格
  4. dgv_details.CurrentCell=dgv_details[0,0];
  5. //开始编辑状态
  6. dgv_details.BeginEdit(false);

3、定制自动生成绑定了列
实现:

  1. dgv_details.AutoGenerateColumns=false;

4、设置列的背景色
实现:

  1. ColorGridReadOnlyColor=Color.LightGoldenrodYellow;
  2. dgv_details.Columns[1].DefaultCellStyle.BackColor=WinKeys.GridReadOnlyColor;

5、DataGridView单元格验证的设计的问题
问题:绑定还是不绑定?
1)绑定的优势:比较简单,代码少。
2)绑定得缺点:DataGridView中的数据受数据源的影响(主键约束、值类型约束)。不一至时会激发DataError事件,输入的内容无法保存到单元格中和数据源中。特殊的验证(比如长度、格式等)还是需要另外写代码实现。
关于增加行的问题。增加新行时多主键的验证有问题,而且验证不通过时会将新行全部删除。限制很多,很不方便。
3)非绑定的优势:验证等处理比较灵活。不受数据源的约束。
4)非绑定得缺点:显示和向数据库更新数据时需要比较多的代码实现,效率比较低。
5)总的感觉在处理验证比较麻烦的场合,我还是比较喜欢非绑定的方式。如果数据量大,验证比较简单的场合使用绑定模式比较好。

二、DataGridView重绘代码

1、CellFormatting事件,一般重绘单元格属性。

  1. privateBitmaphighPriImage;
  2. privateBitmapmediumPriImage;
  3. privateBitmaplowPriImage;
  4. privatevoiddataGridView1_CellFormatting(objectsender,
  5. System.Windows.Forms.DataGridViewCellFormattingEventArgse)
  6. {
  7. //SetthebackgroundtoredfornegativevaluesintheBalancecolumn.
  8. if(dataGridView1.Columns[e.ColumnIndex].Name.Equals("Balance"))
  9. {
  10. Int32intValue;
  11. if(Int32.TryParse((String)e.Value,outintValue)&&
  12. (intValue<0))
  13. {
  14. e.CellStyle.BackColor=Color.Red;
  15. e.CellStyle.SelectionBackColor=Color.DarkRed;
  16. }
  17. }
  18. //ReplacestringvaluesinthePrioritycolumnwithimages.
  19. if(dataGridView1.Columns[e.ColumnIndex].Name.Equals("Priority"))
  20. {
  21. //Ensurethatthevalueisastring.
  22. StringstringValue=e.Valueasstring;
  23. if(stringValue==null)return;
  24. //SetthecellToolTiptothetextvalue.
  25. DataGridViewCellcell=dataGridView1[e.ColumnIndex,e.RowIndex];
  26. cell.ToolTipText=stringValue;
  27. //Replacethestringvaluewiththeimagevalue.
  28. switch(stringValue)
  29. {
  30. case"high":
  31. e.Value=highPriImage;
  32. break;
  33. case"medium":
  34. e.Value=mediumPriImage;
  35. break;
  36. case"low":
  37. e.Value=lowPriImage;
  38. break;
  39. }
  40. }
  41. }

2、CellPainting事件,一般用于合并单元格用
Windows Forms DataGridView 没有提供合并单元格的功能,要实现合并单元格的功能就要在CellPainting事件中使用Graphics.DrawLine和 Graphics.DrawString 自己来“画”。
下面的代码可以对DataGridView第1列内容相同的单元格进行合并:

  1. #region"合并单元格的测试"
  2. privateint?nextrow=null;
  3. privateint?nextcol=null;
  4. privatevoiddataGridView1_CellFormatting(objectsender,System.Windows.Forms.DataGridViewCellFormattingEventArgse)
  5. {
  6. if(this.dataGridView1.Columns["description"].Index==e.ColumnIndex&&e.RowIndex>=0)
  7. {
  8. if(this.nextcol!=null&e.ColumnIndex==this.nextcol)
  9. {
  10. e.CellStyle.BackColor=Color.LightBlue;
  11. this.nextcol=null;
  12. }
  13. if(this.nextrow!=null&e.RowIndex==nextrow)
  14. {
  15. e.CellStyle.BackColor=Color.LightPink;
  16. this.nextrow=null;
  17. }
  18. if(e.RowIndex!=this.dataGridView1.RowCount-1)
  19. {
  20. if(e.Value.ToString()==this.dataGridView1.Rows[e.RowIndex+1].Cells[e.ColumnIndex].Value.ToString())
  21. {
  22. e.CellStyle.BackColor=Color.LightPink;
  23. nextrow=e.RowIndex+1;
  24. }
  25. }
  26. }
  27. if(this.dataGridView1.Columns["name"].Index==e.ColumnIndex&&e.RowIndex>=0)
  28. {
  29. if(e.Value.ToString()==this.dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex+1].Value.ToString())
  30. {
  31. e.CellStyle.BackColor=Color.LightBlue;
  32. nextcol=e.ColumnIndex+1;
  33. }
  34. }
  35. }
  36. //==========================
  37. //绘制单元格
  38. privatevoiddataGridView1_CellPainting(objectsender,System.Windows.Forms.DataGridViewCellPaintingEventArgse)
  39. {
  40. //纵向合并
  41. if(this.dataGridView1.Columns["description"].Index==e.ColumnIndex&&e.RowIndex>=0)
  42. {
  43. using(
  44. BrushgridBrush=newSolidBrush(this.dataGridView1.GridColor),
  45. backColorBrush=newSolidBrush(e.CellStyle.BackColor))
  46. {
  47. using(PengridLinePen=newPen(gridBrush))
  48. {
  49. //擦除原单元格背景
  50. e.Graphics.FillRectangle(backColorBrush,e.CellBounds);
  51. ////绘制线条,这些线条是单元格相互间隔的区分线条,
  52. ////因为我们只对列name做处理,所以datagridview自己会处理左侧和上边缘的线条
  53. if(e.RowIndex!=this.dataGridView1.RowCount-1)
  54. {
  55. if(e.Value.ToString()!=this.dataGridView1.Rows[e.RowIndex+1].Cells[e.ColumnIndex].Value.ToString())
  56. {
  57. e.Graphics.DrawLine(gridLinePen,e.CellBounds.Left,e.CellBounds.Bottom-1,
  58. e.CellBounds.Right-1,e.CellBounds.Bottom-1);//下边缘的线
  59. //绘制值
  60. if(e.Value!=null)
  61. {
  62. e.Graphics.DrawString((String)e.Value,e.CellStyle.Font,
  63. Brushes.Crimson,e.CellBounds.X+2,
  64. e.CellBounds.Y+2,StringFormat.GenericDefault);
  65. }
  66. }
  67. }
  68. else
  69. {
  70. e.Graphics.DrawLine(gridLinePen,e.CellBounds.Left,e.CellBounds.Bottom-1,
  71. e.CellBounds.Right-1,e.CellBounds.Bottom-1);//下边缘的线
  72. //绘制值
  73. if(e.Value!=null)
  74. {
  75. e.Graphics.DrawString((String)e.Value,e.CellStyle.Font,
  76. Brushes.Crimson,e.CellBounds.X+2,
  77. e.CellBounds.Y+2,StringFormat.GenericDefault);
  78. }
  79. }
  80. //右侧的线
  81. e.Graphics.DrawLine(gridLinePen,e.CellBounds.Right-1,
  82. e.CellBounds.Top,e.CellBounds.Right-1,
  83. e.CellBounds.Bottom-1);
  84. e.Handled=true;
  85. }
  86. }
  87. }
  88. //横向合并
  89. if(this.dataGridView1.Columns["name"].Index==e.ColumnIndex&&e.RowIndex>=0)
  90. {
  91. using(
  92. BrushgridBrush=newSolidBrush(this.dataGridView1.GridColor),
  93. backColorBrush=newSolidBrush(e.CellStyle.BackColor))
  94. {
  95. using(PengridLinePen=newPen(gridBrush))
  96. {
  97. //擦除原单元格背景
  98. e.Graphics.FillRectangle(backColorBrush,e.CellBounds);
  99. if(e.Value.ToString()!=this.dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex+1].Value.ToString())
  100. {
  101. //右侧的线
  102. e.Graphics.DrawLine(gridLinePen,e.CellBounds.Right-1,e.CellBounds.Top,
  103. e.CellBounds.Right-1,e.CellBounds.Bottom-1);
  104. //绘制值
  105. if(e.Value!=null)
  106. {
  107. e.Graphics.DrawString((String)e.Value,e.CellStyle.Font,
  108. Brushes.Crimson,e.CellBounds.X+2,
  109. e.CellBounds.Y+2,StringFormat.GenericDefault);
  110. }
  111. }
  112. //下边缘的线
  113. e.Graphics.DrawLine(gridLinePen,e.CellBounds.Left,e.CellBounds.Bottom-1,
  114. e.CellBounds.Right-1,e.CellBounds.Bottom-1);
  115. e.Handled=true;
  116. }
  117. }
  118. }
  119. }
  120. #endregion

三、在GridView中如何格式化Money型字段(downmoon)?

  1. <asp:GridViewID="GridView1"runat="server"AutoGenerateColumns="False"DataKeyNames="PKID"
  2. DataMember="DefaultView"DataSourceID="SqlDataSource1">
  3. <Columns>
  4. <asp:BoundFieldDataField="PKID"HeaderText="PKID"InsertVisible="False"ReadOnly="True"
  5. SortExpression="PKID"/>
  6. <asp:TemplateField>
  7. <HeaderTemplate>
  8. amount</HeaderTemplate>
  9. <ItemTemplate>
  10. <asp:LabelID="txtMoney"Text='<%#Decimal.Parse(DataBinder.Eval(Container.DataItem,"amount").ToString())%>'runat="server"/>
  11. </ItemTemplate>
  12. </asp:TemplateField>
  13. <asp:BoundFieldDataField="TestID"HeaderText="TestID"SortExpression="TestID"/>
  14. <asp:BoundFieldDataField="testString"HeaderText="testString"SortExpression="testString"/>
  15. </Columns>
  16. </asp:GridView>

这段代码中,
amount为Money型字段,无论如何只能显示成
1234.5600
而不能显示成
1,234.56

  1. <asp:BoundFieldDataField="amount"HeaderText="amount"DataFormatString="{0:n2}"/>
  2. <asp:BoundFieldDataField="amount"HeaderText="amount"DataFormatString="{0:c2}"/>

也不行!
后来在MSDN上找到了答案

  1. <asp:BoundFieldDataField="amount"HeaderText="amount"DataFormatString="{0:#,###.00}"HtmlEncode="False"/>

关键在于HtmlEncode="False"

http://blogs.msdn.com/danielfe/archive/2006/02/08/527628.aspx

(源文:http://blog.csdn.net/downmoon/archive/2007/11/01/1860611.aspx

四、DataGridView合并单元格 编辑单元格

同事的一个项目需要将DataGridView单元格中的内容分不同颜色显示,想了想只有重绘了。
这种方法还可以用做合并单元格。

参考代码:

  1. privatevoiddataGridView1_CellPainting(objectsender,DataGridViewCellPaintingEventArgse)
  2. {
  3. if(e.RowIndex==0&&e.ColumnIndex>=0)
  4. {
  5. intleft=e.CellBounds.Left;
  6. inttop=e.CellBounds.Top;
  7. intright=e.CellBounds.Right;
  8. intbottom=e.CellBounds.Bottom;
  9. e.Graphics.FillRectangle(newSolidBrush(Color.White),e.CellBounds);
  10. e.Handled=true;
  11. BrushgridBrush=newSolidBrush(this.dataGridView1.GridColor);
  12. PengridLinePen=newPen(gridBrush);
  13. e.Graphics.DrawLine(gridLinePen,right-1,
  14. top,right-1,
  15. bottom-1);
  16. e.Graphics.DrawLine(gridLinePen,left,
  17. bottom-1,right,
  18. bottom-1);
  19. Brushb1=newSolidBrush(Color.Black);
  20. e.Graphics.DrawString((String)e.Value,e.CellStyle.Font,
  21. b1,left+2,
  22. top+1,StringFormat.GenericDefault);
  23. Brushb2=newSolidBrush(Color.Red);
  24. e.Graphics.DrawString((String)e.Value,e.CellStyle.Font,
  25. b2,left+2,
  26. top+10,StringFormat.GenericDefault);
  27. }
  28. DataGridViewSelectedCellCollectiondgvscc=this.dataGridView1.SelectedCells;
  29. foreach(DataGridViewCelldgvcindgvscc)
  30. {
  31. if(e.RowIndex==0
  32. &&e.RowIndex==dgvc.RowIndex
  33. &&e.ColumnIndex==dgvc.ColumnIndex)
  34. {
  35. intleft=e.CellBounds.Left;
  36. inttop=e.CellBounds.Top;
  37. intright=e.CellBounds.Right;
  38. intbottom=e.CellBounds.Bottom;
  39. //绘制背景,覆盖单元格区域
  40. e.Graphics.FillRectangle(newSolidBrush(Color.FromArgb(10,36,106)),e.CellBounds);
  41. //绘制边框
  42. BrushgridBrush=newSolidBrush(this.dataGridView1.GridColor);
  43. PengridLinePen=newPen(gridBrush);
  44. e.Graphics.DrawLine(gridLinePen,right-1,
  45. top,right-1,
  46. bottom-1);
  47. e.Graphics.DrawLine(gridLinePen,left,
  48. bottom-1,right,
  49. bottom-1);
  50. //绘制文字
  51. Brushb1=newSolidBrush(Color.White);
  52. e.Graphics.DrawString((String)e.Value,e.CellStyle.Font,
  53. b1,left+2,
  54. top+1,StringFormat.GenericDefault);
  55. Brushb2=newSolidBrush(Color.White);
  56. e.Graphics.DrawString((String)e.Value,e.CellStyle.Font,
  57. b2,left+2,
  58. top+10,StringFormat.GenericDefault);
  59. }
  60. }
  61. e.Handled=true;
  62. }

感谢各位作者。

分享到:
评论

相关推荐

    datagridview编程技巧

    DataGridView控件用法合集 56. DataGridView根据值不同在另一列中显示相应图片 57. DataGridView中显示进度条(ProgressBar) 58. DataGridView中添加MaskedTextBox 59. DataGridView中Enter键按下焦点移至旁边的...

    DataGridView控件用法合集

    对datagridview 控件的用法、技巧提供详细的实例,参考价值较大。

    Visual C++ 2005 编程技巧大全光盘

    包括ToolStrip控件应用、泛型应用、注册表管理、WMI管理规范使用、XML文件处理、多线程处理、程序异常处理、文件压缩及解压缩、文件加密解密、文件访问权限、API函数调用、GDI+图像文字特效处理、数据更新并发冲突...

    C#开发app资料合集

    使用VS中自带的C#开发app的资料,包括传值、datagridview等使用技巧以及代码参考

    C#开发经验技巧宝典

    0826 将DataGridView控件中的数据导入Excel 495 0827 无法获取自定义环境变量的值 496 0828 将组件放到COM+服务器上去 496 0829 调用非托管的DLL文件 497 0830 如何将GridView控件数据导入Word 497 0831 ...

    C#编程经验技巧宝典

    14 &lt;br&gt;0028 “///”符号的使用技巧 14 &lt;br&gt;0029 使用注释取消程序语句的执行 15 &lt;br&gt;2.2 语句 15 &lt;br&gt;0030 跳转语句GOTO的使用 15 &lt;br&gt;0031 Continue语句的使用 16 &lt;br&gt;0032 Break...

    CSharp常用技术总结(DOC)

    3、将查询结果集赋给dateGridView 4、让文本框同步显示dataGridView中的当前记录 5、根据所选的查询条件动态组合SQL语句 6、用数据库表中的指定列值初始化checkListBox控件 7、利用循环将查询结果赋给含checkBox列...

    asp.net知识库

    .net中的正则表达式使用高级技巧 (一) C#静态成员和方法的学习小结 C#中结构与类的区别 C#中 const 和 readonly 的区别 利用自定义属性,定义枚举值的详细文本 Web标准和ASP.NET - 第一部分 XHTML介绍 在ASP.NET...

    《C#和.NET 3.0第一步--适用Visual Studio 2005与Visual Studio 2008》随书配套光盘

    第二篇包含了C#语言相关的高级概念,如集合对象、泛型、程序集、多线程等等,重点讲述了VC#中数据处理的相关技术,如ADO.NET编程、数据集、数据绑定、DataGridView控件、打印和报表等,同时,对面向对象的分析与设计...

    C# Winform数据库应用设计(附开发案例

    932 Datagridview控件的使用. 221 9 综合示例 226 仟务实训部分.… 229 1:航班查询窗体设计 29 2:显示所有航班信息 232 3:根据两地査询航班 .233 4:航班详细信息查询 234 巩固练习 235 第10章课程总复习… …)误!...

Global site tag (gtag.js) - Google Analytics