DataGridView使用
- DataGridView控件概述
- DataGridView 控件代码目录(Windows 窗体)
- 未绑定数据列
- 定义:可能想要显示并非来自数据源的一列数据,这种列称为未绑定列.
- 数据格式示例
- 如何:设置 Windows 窗体 DataGridView 控件中的数据格式
- DefaultCellStyle
- 如何:自定义数据格式
- 实现 DataGridView.CellFormatting 事件的处理程序,该处理程序根据单元格的列和值更改单元格的显示方式
- 如何:设置 Windows 窗体 DataGridView 控件中的数据格式
- 数据验证示例
- 验证DataGridView控件中的数据:实现 DataGridView 控件的 CellValidating 和 CellEndEdit 事件的处理程序。如果单元格值验证失败,请将 ValidatingEventArgs 类的 Cancel 属性设置为 true。 这将导致 DataGridView 控件阻止光标离开该单元格。 将该行的 ErrorText 属性设置为解释性字符串。 这将显示错误图标,其工具提示将包含此错误文本。在 CellEndEdit 事件处理程序中,将该行的 ErrorText 属性设置为空字符串。 只有当单元格退出编辑模式(如果验证失败,则不能退出单元格)时,才能发生 CellEndEdit 事件。
- 处理DataGridView输入数据时发生的错误:Windows 窗体 DataGridView 控件通过公开 DataError 事件来轻松实现此类错误的处理;当数据存储区检测到约束冲突或违反业务规则时将引发该事件。
- 外观自定义示例
- 通
过行模板自定义DataGridView中的行:RowTemplate与RowsDefaultCellStyle
属性相比,行模板能更好地控制行的外观和行为。 使用行模板,可以设置包括DefaultCellStyle 在内的任何
DataGridViewRow 属性。
- 通
- 行为自定义示例
- 指定 Windows 窗体 DataGridView 控件的编辑模式
- 在编辑模式EditMode中,用户可以更改单元格的值。 也可以防止单元格进入编辑模式,除非调用 BeginEdit 方法。
- 为 Windows 窗体 DataGridView 控件中的新行指定默认值
- 当应用程序为新添加的行填充默认值时,能使数据输入变得更方便。 通过 DataGridView 类,可以使用 DefaultValuesNeeded 事件填充默认值。 此事件在用户进入新记录的行时引发。 在代码处理此事件时,可以用选择的值填充所需的单元格。
- 为DataGridView 控件中的单个单元格添加工具提示
- DataGridViewCell.ToolTipText
- 使用户能够将多个单元格从DataGridView 控件复制到剪贴板
- 启用单元格复制时,其他应用程序将能够很容易地通过 Clipboard 访问 DataGridView 控件中的数据。
- DataGridView.ClipboardCopyMode
- 示例
- 指定 Windows 窗体 DataGridView 控件的编辑模式
- 列操作示例
- 更改 Windows 窗体 DataGridView列的顺序
- DisplayIndex属性
- 更改 Windows 窗体 DataGridView列的顺序
- 行和列调整大小示例
- 列调整大小
选中某一列,设置列的AutoSizeMode属性,可以自动调整列的宽度。
- 列调整大小
- 选择示例
- 获取选中单元格的数量
- dgv_Detail.GetCellCount(DataGridViewElementStates.Selected)
- 获取选中行的数量
- dgv_Detail.Rows.GetRowCount(DataGridViewElementStates.Selected)
- 获取选中列的数量
- dgv_Detail.Columns.GetColumnCount(DataGridViewElementStates.Selected)
- 判断是否选择了所有的单元格
- dgv_Detail.AreAllCellsSelected
- 获取选中单元格的数量
- 高级自定义示例
- 高级数据示例
- 未绑定数据列
- DataGridView 控件代码目录(Windows 窗体)
- Windows 窗体 DataGridView 控件中的列类型
-
与基于文本的值一起使用。 在绑定到数字和字符串时自动生成。
-
与 Boolean 和 CheckState 值一起使用。 在绑定到这些类型的值时自动生成。
-
用于显示图像。 在绑定到字节数组、Image 对象或 Icon 对象时自动生成。
-
用于在单元格中显示按钮。 不会在绑定时自动生成。 通常用作未绑定列。
-
用于在单元格中显示下拉列表。 不会在绑定时自动生成。 通常手动进行数据绑定。
-
用于在单元格中显示链接。 不会在绑定时自动生成。 通常手动进行数据绑定。
-
- 在 Windows 窗体 DataGridView 控件中显示数据
待续
- 调整 Windows 窗体 DataGridView 控件中列和行的大小
待续
- 对 Windows 窗体 DataGridView 控件中的数据排序
- 如何:设置 Windows 窗体 DataGridView 控件中列的排序模式
在 DataGridView 控件中,默认情况下文本框列使用自动排序,而其他列类型不自动排序。 有时您会希望重写这些默认设置。 例如,可以显示图像来替换文本、数字或枚举单元格值。 虽然无法排序图像,但可以排序它们表示的基础值。 SortMode = DataGridViewColumnSortMode.Automatic;
- 自定义 Windows 窗体 DataGridView 控件中的排序方式
- 以编程方式排序
private void sortButton_Click(object sender, System.EventArgs e)
{
// Check which column is selected, otherwise set NewColumn to null.
DataGridViewColumn newColumn =
dataGridView1.Columns.GetColumnCount(
DataGridViewElementStates.Selected) == ?
dataGridView1.SelectedColumns[] : null; DataGridViewColumn oldColumn = dataGridView1.SortedColumn;
ListSortDirection direction; // If oldColumn is null, then the DataGridView is not currently sorted.
if (oldColumn != null)
{
// Sort the same column again, reversing the SortOrder.
if (oldColumn == newColumn &&
dataGridView1.SortOrder == SortOrder.Ascending)
{
direction = ListSortDirection.Descending;
}
else
{
// Sort a new column and remove the old SortGlyph.
direction = ListSortDirection.Ascending;
oldColumn.HeaderCell.SortGlyphDirection = SortOrder.None;
}
}
else
{
direction = ListSortDirection.Ascending;
} // If no column has been selected, display an error dialog box.
if (newColumn == null)
{
MessageBox.Show("Select a single column and try again.",
"Error: Invalid Selection", MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
else
{
dataGridView1.Sort(newColumn, direction);
newColumn.HeaderCell.SortGlyphDirection =
direction == ListSortDirection.Ascending ?
SortOrder.Ascending : SortOrder.Descending;
}
} - 使用DataGridView.SortCompare事件自定义排序
private void dataGridView1_SortCompare(object sender,
DataGridViewSortCompareEventArgs e)
{
// Try to sort based on the cells in the current column.
e.SortResult = System.String.Compare(
e.CellValue1.ToString(), e.CellValue2.ToString()); // If the cells are equal, sort based on the ID column.
if (e.SortResult == && e.Column.Name != "ID")
{
e.SortResult = System.String.Compare(
dataGridView1.Rows[e.RowIndex1].Cells["ID"].Value.ToString(),
dataGridView1.Rows[e.RowIndex2].Cells["ID"].Value.ToString());
}
e.Handled = true;
} - 使用 IComparer 接口自定义排序
private void Button1_Click( object sender, EventArgs e )
{
if ( RadioButton1.Checked == true )
{
DataGridView1.Sort( new RowComparer( SortOrder.Ascending ) );
}
else if ( RadioButton2.Checked == true )
{
DataGridView1.Sort( new RowComparer( SortOrder.Descending ) );
}
} private class RowComparer : System.Collections.IComparer
{
private static int sortOrderModifier = ; public RowComparer(SortOrder sortOrder)
{
if (sortOrder == SortOrder.Descending)
{
sortOrderModifier = -;
}
else if (sortOrder == SortOrder.Ascending)
{
sortOrderModifier = ;
}
} public int Compare(object x, object y)
{
DataGridViewRow DataGridViewRow1 = (DataGridViewRow)x;
DataGridViewRow DataGridViewRow2 = (DataGridViewRow)y; // Try to sort based on the Last Name column.
int CompareResult = System.String.Compare(
DataGridViewRow1.Cells[].Value.ToString(),
DataGridViewRow2.Cells[].Value.ToString()); // If the Last Names are equal, sort based on the First Name.
if ( CompareResult == )
{
CompareResult = System.String.Compare(
DataGridViewRow1.Cells[].Value.ToString(),
DataGridViewRow2.Cells[].Value.ToString());
}
return CompareResult * sortOrderModifier;
}
}
- 以编程方式排序
- 如何:设置 Windows 窗体 DataGridView 控件中列的排序模式
- DataGridView的最佳实践
- DataGridView常用问题的解决方法
- 设置选中某一行:dgv.CurrentCell = dgv.Rows[0].Cells[0];
- 获取当前选中行的数据
CurrencyManager cm = (CurrencyManager)dgv.BindingContext[dgv.DataSource]; DataRowView row = (DataRowView)cm.Current;
return row["FiledName"].toString(); - 自动添加序号列
private void dgv_EPC_RowPostPaint(sender,eventArgs)
{
foreach (DataGridViewRow row in dgv_EPC.Rows)
{
row.Cells[].Value = row.Index + ;
}
} - 数据过滤
private void btnEnquiry_Click(object sender, EventArgs e)
{
string filterExpression = string.Empty;
//filter QCPass
if (cbbQCPass.SelectedIndex != && cbbQCPass.SelectedIndex != -)
{
string qcPassRowFilter = string.Format("qcpass = {0}", cbbQCPass.SelectedItem);
filterExpression += qcPassRowFilter;
}
//filter epc
if (!string.IsNullOrWhiteSpace(txtEPC.Text))
{
if (!string.IsNullOrEmpty(filterExpression))
{
filterExpression += " AND ";
}
string epcFilter = string.Format("epc like '{0}%'", txtEPC.Text.Trim());
filterExpression += epcFilter;
}
//filter seq
if (!string.IsNullOrWhiteSpace(txtSEQ.Text))
{
if (!string.IsNullOrEmpty(filterExpression))
{
filterExpression += " AND ";
}
string seqFilter = string.Format("seq like '{0}%'", txtSEQ.Text.Trim());
filterExpression += seqFilter;
} if (!string.IsNullOrEmpty(filterExpression))
{
_dataSource.DefaultView.RowFilter = filterExpression;
}
else
{
_dataSource.DefaultView.RowFilter = string.Empty;
}
} - 添加上下文菜单
//1.在Winform页面添加ContextMenuStrip组件,并添加MenuItem
//2.设定DataGridView的ContextMenu
//3.添加MenuItem事件
private void toolStripMenuItem1_Click(object sender, EventArgs e)
{
Clipboard.SetText(dataGridView1.GetClipboardContent().GetText());
}
//4.添加DataGridView的MouseDown事件,
private void dataGridView1_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Right)
{
DataGridView.HitTestInfo hittestinfo = dataGridView1.HitTest(e.X, e.Y); if (hittestinfo != null && hittestinfo.Type == DataGridViewHitTestType.Cell)
{
DataGridViewCell activeCell = dataGridView1[hittestinfo.ColumnIndex, hittestinfo.RowIndex]; if (!dataGridView1.SelectedCells.Contains(activeCell))
{
dataGridView1.ClearSelection();
activeCell.Selected = true;
}
} }
} - 单击某列时编辑内容:触发CellClick事件,添加dgView.BeginEdit(true)代码。
- 为DataGridView设定数据源时,会引发DataGridView Default Error Dialog错误:在设定dataSource之前先设定dataSoruce = null;
- 0
DataGridView使用的更多相关文章
- [WinForm] DataGridView 绑定 DT && ComboBox 列绑定 Dict
一 需求介绍 一般像枚举类型的数据,我们在数据库里存储着诸如(1.2.3.4-)或者("001"."002"."003"-)此类,但是界面 ...
- [Winform] DataGridView 总结(FAQ)
Q1. 如何使单元格不可编辑? A:设置 ReadOnly 属性,可以设置的对象包括 DataGridViewRow(行).DataGridViewColumn(列).DataGridViewCel ...
- [Winform] DataGridView 中 DataGridViewComboBox 的可编辑
在 DataGridView 中设置的 DataGridViewComboBox,默认是不可编辑的,即使将其列属性 DisplayStyle 设置成 ComboBox 或其他,也无法编辑: 故作如下处 ...
- c#datagridview
//保证显示当前活动单元格 this.Invoke(new Action(() => { dataGridView1.CurrentCell = dataGridView1.Rows[index ...
- DataGridView 在下拉框添加下来事件
DataGridView中有一种下拉框式的列,给这个列添加下拉事件时需要转化一下才可以绑定下拉事件 /// <summary> /// 服务类型 /// </summary> ...
- 设置DataGridView的某个单元格为ComboBox
怎么将DataGridView的 某个单元格设为ComboBox的样式而不是整列都改变样式? 1.最简单的方法:利用DataGridView提供的DataGridViewComboBoxCell. 写 ...
- 用DataGridView导入TXT文件,并导出为XLS文件
使用 DataGridView 控件,可以显示和编辑来自多种不同类型的数据源的表格数据.也可以导出.txt,.xls等格式的文件.今天我们就先介绍一下用DataGridView把导入txt文件,导出x ...
- 图解DataGridView编辑列
WinForm中DataGridView功能强大,除了可以自动绑定数据源外,还可以根据需求编辑列.下面以截图说明添加编辑列的步骤(HoverTreeSCJ 项目实际界面). 1.选择DataGridV ...
- datagridview 单元格格式转换注意
datagridview 单元格内容进行比较时要注意正确写法要用强制转换,否则出错Convert.ToString(grd_order.SelectedRows[0].Cells[1].Value)= ...
- C# DataGridView中指定的单元格不能编辑
注意:DataGridView控件是从.NET Framework 2.0版本开始追加的. ReadOnly属性的使用 DataGridView内所有的单元格不能编辑 当DataGridView.Re ...
随机推荐
- ECMAScript面向对象术语
面向对象术语1.对象ECMA-262 把对象(object)定义为“属性的无序集合,每个属性存放一个原始值.对象或函数”.严格来说,这意味着对象是无特定顺序的值的数组.尽管 ECMAScript 如此 ...
- 第13届景驰-埃森哲杯广东工业大学ACM程序设计大赛--I-填空题
链接:https://www.nowcoder.com/acm/contest/90/I 来源:牛客网 1.题目描述 牛客网是是一个专注于程序员的学习和成长的专业平台,集笔面试系统.课程教育.社群交流 ...
- springboot在yml配置文件中配置类的属性笔记
首先建立一个简单的实体类,我这里以学生为例,并加上@Component和@ConfigurationProperties(prefix ="student")注解,其中prefix ...
- jenkins部署记录
环境规划 主机分配 192.168.2.139 : gitlab 192.168.2.141 : jenkins 192.168.2.142 : haproxy01 192.168.2.143 :ha ...
- mongo数据库相关目录
mongodb的docker化安装 mongodb的windows系统下安装 grafana使用Prometheus数据源监控mongo数据库 mongodb副本集的docker化安装 mongodb ...
- Java源码解析——集合框架(五)——HashMap源码分析
HashMap源码分析 HashMap的底层实现是面试中问到最多的,其原理也更加复杂,涉及的知识也越多,在项目中的使用也最多.因此清晰分析出其底层源码对于深刻理解其实现有重要的意义,jdk1.8之后其 ...
- pads怎么高亮网络
pads怎么高亮网络 选择完整个网络----再按CTRL+H 就高亮了. 取消高亮是,选择需要取消高亮的整个网络,按 CTRL+U 就取消了. PADS在生成Gerber时过孔盖油设置方法 PADS2 ...
- 爬虫之request模块高级
一.cookie&session cookie:服务器端使用cookie来记录客户端的状态信息 实现流程: 执行登陆操作(获取cookie) 在发起个人主页请求时,需要将cookie携带到该请 ...
- dns文件
1.dns简介 dns为域名解析系统,当本地浏览器输入域名访问网站时,如果本地host中没有配置域名与IP的对应关系,那么域名信息将会被发送到dns服务器上,由dns服务器将域名解析为IP(过程较为复 ...
- Python自动化运维——文件内容差异对比
Infi-chu: http://www.cnblogs.com/Infi-chu/ 模块:difflib 安装:Python版本大于等于2.3系统自带 功能:对比文本之间的差异,而且支持输出可读性比 ...