现在的位置: 首页 > 综合 > 正文

DataGridView使用技巧

2013年09月17日 ⁄ 综合 ⁄ 共 9863字 ⁄ 字号 评论关闭

收集一些在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
  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.         }

感谢各位作者。

抱歉!评论已关闭.