DataGridView使用技巧

收集一些在DataGridVeiw使用技巧,备用。

一、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. Color GridReadOnlyColor = Color.LightGoldenrodYellow;
  2. dgv_details.Columns[1].DefaultCellStyle.BackColor = WinKeys.GridReadOnlyColor;

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

二、DataGridView重绘代码

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

  1. private Bitmap highPriImage;
  2. private Bitmap mediumPriImage;
  3. private Bitmap lowPriImage;
  4. private void dataGridView1_CellFormatting(object sender,
  5.         System.Windows.Forms.DataGridViewCellFormattingEventArgs e)
  6.     {
  7. // Set the background to red for negative values in the Balance column.
  8. if (dataGridView1.Columns[e.ColumnIndex].Name.Equals("Balance"))
  9.         {
  10.             Int32 intValue;
  11. if (Int32.TryParse((String)e.Value, out intValue) &&
  12.                 (intValue < 0))
  13.             {
  14.                 e.CellStyle.BackColor = Color.Red;
  15.                 e.CellStyle.SelectionBackColor = Color.DarkRed;
  16.             }
  17.         }
  18. // Replace string values in the Priority column with images.
  19. if (dataGridView1.Columns[e.ColumnIndex].Name.Equals("Priority"))
  20.         {
  21. // Ensure that the value is a string.
  22.             String stringValue = e.Value as string;
  23. if (stringValue == null) return;
  24. // Set the cell ToolTip to the text value.
  25.             DataGridViewCell cell = dataGridView1[e.ColumnIndex, e.RowIndex];
  26.             cell.ToolTipText = stringValue;
  27. // Replace the string value with the image value.
  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. private int? nextrow = null;
  3. private int? nextcol = null;
  4. private void dataGridView1_CellFormatting(object sender, System.Windows.Forms.DataGridViewCellFormattingEventArgs e)
  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. private void dataGridView1_CellPainting(object sender, System.Windows.Forms.DataGridViewCellPaintingEventArgs e)
  39. {
  40. //纵向合并
  41. if (this.dataGridView1.Columns["description"].Index == e.ColumnIndex && e.RowIndex >= 0)
  42.     {
  43. using (
  44.             Brush gridBrush = new SolidBrush(this.dataGridView1.GridColor),
  45.             backColorBrush = new SolidBrush(e.CellStyle.BackColor))
  46.         {
  47. using (Pen gridLinePen = new Pen(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.             Brush gridBrush = new SolidBrush(this.dataGridView1.GridColor),
  93.             backColorBrush = new SolidBrush(e.CellStyle.BackColor))
  94.         {
  95. using (Pen gridLinePen = new Pen(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. DataMember="DefaultView" DataSourceID="SqlDataSource1">
  2. SortExpression="PKID" />
  3.                            amount

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

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

关键在于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. private void dataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
  2.         {
  3. if (e.RowIndex == 0 && e.ColumnIndex >= 0)
  4.             {
  5. int left = e.CellBounds.Left;
  6. int top = e.CellBounds.Top;
  7. int right = e.CellBounds.Right;
  8. int bottom = e.CellBounds.Bottom;
  9.                 e.Graphics.FillRectangle(new SolidBrush(Color.White), e.CellBounds);
  10.                 e.Handled = true;
  11.                 Brush gridBrush = new SolidBrush(this.dataGridView1.GridColor);
  12.                 Pen gridLinePen = new Pen(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.                 Brush b1 = new SolidBrush(Color.Black);
  20.                 e.Graphics.DrawString((String)e.Value, e.CellStyle.Font,
  21.                                         b1, left + 2,
  22.                                         top + 1, StringFormat.GenericDefault);
  23.                 Brush b2 = new SolidBrush(Color.Red);
  24.                 e.Graphics.DrawString((String)e.Value, e.CellStyle.Font,
  25.                                         b2, left + 2,
  26.                                         top + 10, StringFormat.GenericDefault);
  27.             }
  28.             DataGridViewSelectedCellCollection dgvscc = this.dataGridView1.SelectedCells;
  29. foreach (DataGridViewCell dgvc in dgvscc)
  30.             {
  31. if (e.RowIndex == 0
  32.                         && e.RowIndex == dgvc.RowIndex
  33.                         && e.ColumnIndex == dgvc.ColumnIndex)
  34.                     {
  35. int left = e.CellBounds.Left;
  36. int top = e.CellBounds.Top;
  37. int right = e.CellBounds.Right;
  38. int bottom = e.CellBounds.Bottom;
  39. // 绘制背景,覆盖单元格区域
  40.                         e.Graphics.FillRectangle(new SolidBrush(Color.FromArgb(10,36,106)), e.CellBounds);
  41. // 绘制边框
  42.                         Brush gridBrush = new SolidBrush(this.dataGridView1.GridColor);
  43.                         Pen gridLinePen = new Pen(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.                         Brush b1 = new SolidBrush(Color.White);
  52.                         e.Graphics.DrawString((String)e.Value, e.CellStyle.Font,
  53.                                                 b1, left + 2,
  54.                                                 top + 1, StringFormat.GenericDefault);
  55.                         Brush b2 = new SolidBrush(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控件用法合集 1. DataGridView当前的单元格属性取得、变更 2. DataGridView编辑属性 3. DataGridView最下面一列新追加行非表示 4. DataGridView判断当前选中行是否为新追加的行 5. DataGridView删除行可否设定 6. DataGridView行列不表示和删除 7. DataGridView行列宽度高度设置为不能编辑 8. DataGridView行高列幅自动调整 9. DataGridView指定行列冻结 10. DataGridView列顺序变更可否设定 11. DataGridView行复数选择 12. DataGridView选择的行、列、单元格取得 13. DataGridView指定单元格是否表示 14. DataGridView表头部单元格取得 15. DataGridView表头部单元格文字列设定 16. DataGridView选择的部分拷贝至剪贴板 17. DataGridView粘贴 18. DataGridView单元格上ToolTip表示设定(鼠标移动到相应单元格上时,弹出说明信息) 19. DataGridView中的ContextMenuStrip属性 20. DataGridView指定滚动框位置 21. DataGridView手动追加列 22. DataGridView全体分界线样式设置 23. DataGridView根据单元格属性更改显示内容 24. DataGridView新追加行的行高样式设置る 25. DataGridView新追加行单元格默认值设置 26. DataGridView单元格数据错误标签表示 27. DataGridView单元格内输入值正确性判断 28. DataGridView单元格输入错误值事件的捕获 29. DataGridView行排序(点击列表头自动排序的设置) 30. DataGridView自动行排序(新追加值也会自动排序) 31. DataGridView自动行排序禁止情况下的排序 32. DataGridView指定列指定排序 33. DataGridView单元格样式设置 34. DataGridView文字表示位置的设定 35. DataGridView单元格内文字列换行 36. DataGridView单元格DBNull值表示的设定 37. DataGridView单元格样式格式化 38. DataGridView指定单元格颜色设定 39. DataGridView单元格文字字体设置 40. DataGridView根据单元格值设定单元格样式 41. DataGridView设置单元格背景颜色 42. DataGridView行样式描画 43. DataGridView显示行号 44. DataGridView焦点所在单元格焦点框不显示的设定 45. DataGridView列中显示选择框CheckBox 46. DataGridView中显示下拉框ComboBox 47. DataGridView单击打开下拉框 48. DataGridView中显示按钮 49. DataGridView中显示链接 50. DataGridView中显示图像 51. DataGridView编辑中单元格控件取得 52. DataGridView输入自动完成 53. DataGridView单元格编辑时键盘KEY事件取得 54. DataGridView下拉框(ComboBox)单元格编辑时事件取得 55. DataGridView下拉框(ComboBox)单元格允许文字输入设定 56. DataGridView根据值不同在另一列中显示相应图片 57. DataGridView中显示进度条(ProgressBar) 58. DataGridView中添加MaskedTextBox 59. DataGridView中Enter键按下焦点移至旁边的单元格 60. DataGridView行集合化(Group)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值