1. DataGridView控件概述
    1. DataGridView 控件代码目录(Windows 窗体)
      1. 未绑定数据列
        1. 定义:可能想要显示并非来自数据源的一列数据,这种列称为未绑定列.
      2. 数据格式示例
        1. 如何:设置 Windows 窗体 DataGridView 控件中的数据格式
          1. DefaultCellStyle
        2. 如何:自定义数据格式
          1. 实现 DataGridView.CellFormatting 事件的处理程序,该处理程序根据单元格的列和值更改单元格的显示方式
      3. 数据验证示例
        1. 验证DataGridView控件中的数据:实现 DataGridView 控件的 CellValidating 和 CellEndEdit 事件的处理程序。如果单元格值验证失败,请将 ValidatingEventArgs 类的 Cancel 属性设置为 true。 这将导致 DataGridView 控件阻止光标离开该单元格。 将该行的 ErrorText 属性设置为解释性字符串。 这将显示错误图标,其工具提示将包含此错误文本。在 CellEndEdit 事件处理程序中,将该行的 ErrorText 属性设置为空字符串。 只有当单元格退出编辑模式(如果验证失败,则不能退出单元格)时,才能发生 CellEndEdit 事件。
        2. 处理DataGridView输入数据时发生的错误:Windows 窗体 DataGridView 控件通过公开 DataError 事件来轻松实现此类错误的处理;当数据存储区检测到约束冲突或违反业务规则时将引发该事件。
      4. 外观自定义示例

        1. 过行模板自定义DataGridView中的行:RowTemplate与RowsDefaultCellStyle
          属性相比,行模板能更好地控制行的外观和行为。 使用行模板,可以设置包括DefaultCellStyle 在内的任何
          DataGridViewRow 属性。
      5. 行为自定义示例
        1. 指定 Windows 窗体 DataGridView 控件的编辑模式
          1. 在编辑模式EditMode中,用户可以更改单元格的值。 也可以防止单元格进入编辑模式,除非调用 BeginEdit 方法。
        2. 为 Windows 窗体 DataGridView 控件中的新行指定默认值
          1. 当应用程序为新添加的行填充默认值时,能使数据输入变得更方便。 通过 DataGridView 类,可以使用 DefaultValuesNeeded 事件填充默认值。 此事件在用户进入新记录的行时引发。 在代码处理此事件时,可以用选择的值填充所需的单元格。
        3. 为DataGridView 控件中的单个单元格添加工具提示
          1. DataGridViewCell.ToolTipText
        4. 使用户能够将多个单元格从DataGridView 控件复制到剪贴板
          1. 启用单元格复制时,其他应用程序将能够很容易地通过 Clipboard 访问 DataGridView 控件中的数据。
          2. DataGridView.ClipboardCopyMode
          3. 示例
            1.  
      6. 列操作示例
        1. 更改 Windows 窗体 DataGridView列的顺序
          1. DisplayIndex属性
      7. 行和列调整大小示例
        1. 列调整大小

          选中某一列,设置列的AutoSizeMode属性,可以自动调整列的宽度。

      8. 选择示例
        1. 获取选中单元格的数量
          1. dgv_Detail.GetCellCount(DataGridViewElementStates.Selected)
        2. 获取选中行的数量
          1. dgv_Detail.Rows.GetRowCount(DataGridViewElementStates.Selected)
        3. 获取选中列的数量
          1. dgv_Detail.Columns.GetColumnCount(DataGridViewElementStates.Selected)
        4. 判断是否选择了所有的单元格
          1. dgv_Detail.AreAllCellsSelected
      9. 高级自定义示例
      10. 高级数据示例
  2. Windows 窗体 DataGridView 控件中的列类型
    1. DataGridViewTextBoxColumn

      与基于文本的值一起使用。 在绑定到数字和字符串时自动生成。

    2. DataGridViewCheckBoxColumn

      与 Boolean 和 CheckState 值一起使用。 在绑定到这些类型的值时自动生成。

    3. DataGridViewImageColumn

      用于显示图像。 在绑定到字节数组、Image 对象或 Icon 对象时自动生成。

    4. DataGridViewButtonColumn

      用于在单元格中显示按钮。 不会在绑定时自动生成。 通常用作未绑定列。

    5. DataGridViewComboBoxColumn

      用于在单元格中显示下拉列表。 不会在绑定时自动生成。 通常手动进行数据绑定。

    6. DataGridViewLinkColumn

      用于在单元格中显示链接。 不会在绑定时自动生成。 通常手动进行数据绑定。

  3. 在 Windows 窗体 DataGridView 控件中显示数据

    待续

  4. 调整 Windows 窗体 DataGridView 控件中列和行的大小

    待续

  5. 对 Windows 窗体 DataGridView 控件中的数据排序
    1. 如何:设置 Windows 窗体 DataGridView 控件中列的排序模式

      在 DataGridView 控件中,默认情况下文本框列使用自动排序,而其他列类型不自动排序。 有时您会希望重写这些默认设置。 例如,可以显示图像来替换文本、数字或枚举单元格值。 虽然无法排序图像,但可以排序它们表示的基础值。 SortMode = DataGridViewColumnSortMode.Automatic;

    2. 自定义 Windows 窗体 DataGridView 控件中的排序方式
      1. 以编程方式排序

        1. private void sortButton_Click(object sender, System.EventArgs e)
        2. {
        3. // Check which column is selected, otherwise set NewColumn to null.
        4. DataGridViewColumn newColumn =
        5. dataGridView1.Columns.GetColumnCount(
        6. DataGridViewElementStates.Selected) == ?
        7. dataGridView1.SelectedColumns[] : null;
        8.  
        9. DataGridViewColumn oldColumn = dataGridView1.SortedColumn;
        10. ListSortDirection direction;
        11.  
        12. // If oldColumn is null, then the DataGridView is not currently sorted.
        13. if (oldColumn != null)
        14. {
        15. // Sort the same column again, reversing the SortOrder.
        16. if (oldColumn == newColumn &&
        17. dataGridView1.SortOrder == SortOrder.Ascending)
        18. {
        19. direction = ListSortDirection.Descending;
        20. }
        21. else
        22. {
        23. // Sort a new column and remove the old SortGlyph.
        24. direction = ListSortDirection.Ascending;
        25. oldColumn.HeaderCell.SortGlyphDirection = SortOrder.None;
        26. }
        27. }
        28. else
        29. {
        30. direction = ListSortDirection.Ascending;
        31. }
        32.  
        33. // If no column has been selected, display an error dialog box.
        34. if (newColumn == null)
        35. {
        36. MessageBox.Show("Select a single column and try again.",
        37. "Error: Invalid Selection", MessageBoxButtons.OK,
        38. MessageBoxIcon.Error);
        39. }
        40. else
        41. {
        42. dataGridView1.Sort(newColumn, direction);
        43. newColumn.HeaderCell.SortGlyphDirection =
        44. direction == ListSortDirection.Ascending ?
        45. SortOrder.Ascending : SortOrder.Descending;
        46. }
        47. }
      2. 使用DataGridView.SortCompare事件自定义排序
        1. private void dataGridView1_SortCompare(object sender,
        2. DataGridViewSortCompareEventArgs e)
        3. {
        4. // Try to sort based on the cells in the current column.
        5. e.SortResult = System.String.Compare(
        6. e.CellValue1.ToString(), e.CellValue2.ToString());
        7.  
        8. // If the cells are equal, sort based on the ID column.
        9. if (e.SortResult == && e.Column.Name != "ID")
        10. {
        11. e.SortResult = System.String.Compare(
        12. dataGridView1.Rows[e.RowIndex1].Cells["ID"].Value.ToString(),
        13. dataGridView1.Rows[e.RowIndex2].Cells["ID"].Value.ToString());
        14. }
        15. e.Handled = true;
        16. }
      3. 使用 IComparer 接口自定义排序
        1. private void Button1_Click( object sender, EventArgs e )
        2. {
        3. if ( RadioButton1.Checked == true )
        4. {
        5. DataGridView1.Sort( new RowComparer( SortOrder.Ascending ) );
        6. }
        7. else if ( RadioButton2.Checked == true )
        8. {
        9. DataGridView1.Sort( new RowComparer( SortOrder.Descending ) );
        10. }
        11. }
        12.  
        13. private class RowComparer : System.Collections.IComparer
        14. {
        15. private static int sortOrderModifier = ;
        16.  
        17. public RowComparer(SortOrder sortOrder)
        18. {
        19. if (sortOrder == SortOrder.Descending)
        20. {
        21. sortOrderModifier = -;
        22. }
        23. else if (sortOrder == SortOrder.Ascending)
        24. {
        25. sortOrderModifier = ;
        26. }
        27. }
        28.  
        29. public int Compare(object x, object y)
        30. {
        31. DataGridViewRow DataGridViewRow1 = (DataGridViewRow)x;
        32. DataGridViewRow DataGridViewRow2 = (DataGridViewRow)y;
        33.  
        34. // Try to sort based on the Last Name column.
        35. int CompareResult = System.String.Compare(
        36. DataGridViewRow1.Cells[].Value.ToString(),
        37. DataGridViewRow2.Cells[].Value.ToString());
        38.  
        39. // If the Last Names are equal, sort based on the First Name.
        40. if ( CompareResult == )
        41. {
        42. CompareResult = System.String.Compare(
        43. DataGridViewRow1.Cells[].Value.ToString(),
        44. DataGridViewRow2.Cells[].Value.ToString());
        45. }
        46. return CompareResult * sortOrderModifier;
        47. }
        48. }
  6. DataGridView的最佳实践
  7. DataGridView常用问题的解决方法
    1. 设置选中某一行:dgv.CurrentCell = dgv.Rows[0].Cells[0];
    2. 获取当前选中行的数据
      1. CurrencyManager cm = (CurrencyManager)dgv.BindingContext[dgv.DataSource];
      2.  
      3. DataRowView row = (DataRowView)cm.Current;
      4. return row["FiledName"].toString();
    3. 自动添加序号列
      1. private void dgv_EPC_RowPostPaint(sender,eventArgs)
      2. {
      3. foreach (DataGridViewRow row in dgv_EPC.Rows)
      4. {
      5. row.Cells[].Value = row.Index + ;
      6. }
      7. }
    4. 数据过滤
      1. private void btnEnquiry_Click(object sender, EventArgs e)
      2. {
      3. string filterExpression = string.Empty;
      4. //filter QCPass
      5. if (cbbQCPass.SelectedIndex != && cbbQCPass.SelectedIndex != -)
      6. {
      7. string qcPassRowFilter = string.Format("qcpass = {0}", cbbQCPass.SelectedItem);
      8. filterExpression += qcPassRowFilter;
      9. }
      10. //filter epc
      11. if (!string.IsNullOrWhiteSpace(txtEPC.Text))
      12. {
      13. if (!string.IsNullOrEmpty(filterExpression))
      14. {
      15. filterExpression += " AND ";
      16. }
      17. string epcFilter = string.Format("epc like '{0}%'", txtEPC.Text.Trim());
      18. filterExpression += epcFilter;
      19. }
      20. //filter seq
      21. if (!string.IsNullOrWhiteSpace(txtSEQ.Text))
      22. {
      23. if (!string.IsNullOrEmpty(filterExpression))
      24. {
      25. filterExpression += " AND ";
      26. }
      27. string seqFilter = string.Format("seq like '{0}%'", txtSEQ.Text.Trim());
      28. filterExpression += seqFilter;
      29. }
      30.  
      31. if (!string.IsNullOrEmpty(filterExpression))
      32. {
      33. _dataSource.DefaultView.RowFilter = filterExpression;
      34. }
      35. else
      36. {
      37. _dataSource.DefaultView.RowFilter = string.Empty;
      38. }
      39. }
    5. 添加上下文菜单
      1. //1.在Winform页面添加ContextMenuStrip组件,并添加MenuItem
      2. //2.设定DataGridView的ContextMenu
      3. //3.添加MenuItem事件
      4. private void toolStripMenuItem1_Click(object sender, EventArgs e)
      5. {
      6. Clipboard.SetText(dataGridView1.GetClipboardContent().GetText());
      7. }
      8. //4.添加DataGridView的MouseDown事件,
      9. private void dataGridView1_MouseDown(object sender, MouseEventArgs e)
      10. {
      11. if (e.Button == MouseButtons.Right)
      12. {
      13. DataGridView.HitTestInfo hittestinfo = dataGridView1.HitTest(e.X, e.Y);
      14.  
      15. if (hittestinfo != null && hittestinfo.Type == DataGridViewHitTestType.Cell)
      16. {
      17. DataGridViewCell activeCell = dataGridView1[hittestinfo.ColumnIndex, hittestinfo.RowIndex];
      18.  
      19. if (!dataGridView1.SelectedCells.Contains(activeCell))
      20. {
      21. dataGridView1.ClearSelection();
      22. activeCell.Selected = true;
      23. }
      24. }
      25.  
      26. }
      27. }
    6. 单击某列时编辑内容:触发CellClick事件,添加dgView.BeginEdit(true)代码。
    7. 为DataGridView设定数据源时,会引发DataGridView Default Error Dialog错误:在设定dataSource之前先设定dataSoruce = null;
  8. 0

DataGridView使用的更多相关文章

  1. [WinForm] DataGridView 绑定 DT && ComboBox 列绑定 Dict

    一  需求介绍 一般像枚举类型的数据,我们在数据库里存储着诸如(1.2.3.4-)或者("001"."002"."003"-)此类,但是界面 ...

  2. [Winform] DataGridView 总结(FAQ)

    Q1.  如何使单元格不可编辑? A:设置 ReadOnly 属性,可以设置的对象包括 DataGridViewRow(行).DataGridViewColumn(列).DataGridViewCel ...

  3. [Winform] DataGridView 中 DataGridViewComboBox 的可编辑

    在 DataGridView 中设置的 DataGridViewComboBox,默认是不可编辑的,即使将其列属性 DisplayStyle 设置成 ComboBox 或其他,也无法编辑: 故作如下处 ...

  4. c#datagridview

    //保证显示当前活动单元格 this.Invoke(new Action(() => { dataGridView1.CurrentCell = dataGridView1.Rows[index ...

  5. DataGridView 在下拉框添加下来事件

    DataGridView中有一种下拉框式的列,给这个列添加下拉事件时需要转化一下才可以绑定下拉事件 /// <summary> /// 服务类型 /// </summary> ...

  6. 设置DataGridView的某个单元格为ComboBox

    怎么将DataGridView的 某个单元格设为ComboBox的样式而不是整列都改变样式? 1.最简单的方法:利用DataGridView提供的DataGridViewComboBoxCell. 写 ...

  7. 用DataGridView导入TXT文件,并导出为XLS文件

    使用 DataGridView 控件,可以显示和编辑来自多种不同类型的数据源的表格数据.也可以导出.txt,.xls等格式的文件.今天我们就先介绍一下用DataGridView把导入txt文件,导出x ...

  8. 图解DataGridView编辑列

    WinForm中DataGridView功能强大,除了可以自动绑定数据源外,还可以根据需求编辑列.下面以截图说明添加编辑列的步骤(HoverTreeSCJ 项目实际界面). 1.选择DataGridV ...

  9. datagridview 单元格格式转换注意

    datagridview 单元格内容进行比较时要注意正确写法要用强制转换,否则出错Convert.ToString(grd_order.SelectedRows[0].Cells[1].Value)= ...

  10. C# DataGridView中指定的单元格不能编辑

    注意:DataGridView控件是从.NET Framework 2.0版本开始追加的. ReadOnly属性的使用 DataGridView内所有的单元格不能编辑 当DataGridView.Re ...

随机推荐

  1. BZOJ3668: [Noi2014]起床困难综合症(贪心 二进制)

    Time Limit: 10 Sec  Memory Limit: 512 MBSubmit: 2708  Solved: 1576[Submit][Status][Discuss] Descript ...

  2. java 读取图片并转化为二进制字符串

    本例子的目的在于测试往oracle数据库中插入blob字段 //以下代码源于:https://www.cnblogs.com/ywlx/p/4544179.html public static Str ...

  3. pip安装拓展包--网络超时/Read timed out问题

    pip安装拓展包--网络超时/Read timed out问题 解决方案:切换镜像源(墙皮太厚) 在后面加上: -i https://pypi.douban.com/simple example: p ...

  4. JavaScript--获取页面盒子中鼠标相对于盒子上、左边框的坐标

    分析: 外层边框是浏览器边框,内部盒子是页面的一个盒子,绿点是盒子中鼠标的位置.鼠标相对盒子边框的坐标=页面中(注意不是浏览器)鼠标坐标-盒子相对于浏览器边框的偏移量 第一步:求浏览器边框位置 x=e ...

  5. js 关于字符串转数字及数字保留位数的控制

    1.parseInt()和parseFloat()两个转换函数,将字符串转换成相应的数字. 1.parseInt() parseInt进行转换时,将字符串转成相应的整数.浮点数以后的数字都不要了. p ...

  6. git push之后回滚(撤销)代码

    问题描述:首先,先说明一下,为什么会引发这次的话题,是这样的,我做完功能Agit push之后,2个月后需求部门要求不要功能A了,然后需要在没有功能A的基础上开发,怎么办?赶紧回滚代码呀. 然后我用g ...

  7. TP5部署服务器问题总结

    及最近部署TP5遇到了很多坑,各种环境下都会出现一些问题,下面是我记录的排坑之路 先说最简单的lnmp一键安装包,我用的是1.5稳定版 安装命令:wget http://soft.vpser.net/ ...

  8. 如何导入XML数据 (python3.6.6区别于python2 环境)

    1.在python2中 代码如下图: 放在python3 环境下执行,将出现如下错误: 原因: python2中形如myTree.keys()[0]这样的写法是没有问题的,因为myTree.keys( ...

  9. 003---生成器 & 迭代器

    生成器 & 迭代器 列表生成式 现在有个需求,列表[1, 2, 3, 4, 5, 6, 7, 8, 9],将列表里的每个值加1. 二逼青年版 a = [1, 2, 3, 4, 5, 6, 7, ...

  10. C# 面试题 (一)

    一.C# 理论 1.1.简述 private. protected. public. internal.protected internal 访问修饰符和访问权限 private : 私有成员, 在类 ...