DataGridView 控件 概述
使用 DataGridView 控件,可以显示和编辑来自多种不同类型的数据源的表格数据。
将数据绑定到 DataGridView 控件非常简单和直观,在大多数情况下,只需设置 DataSource 属性即可。在绑定到包含多个列表或表的数据源时,只需将 DataMember 属性设置为指定要绑定的列表或表的字符串即可。可以将许多类型的数据存储区用作数据源,DataGridView 控件支持标准 Windows 窗体数据绑定模型,也可以在没有绑定数据源的情况下操作 DataGridView 控件。
DataGridView 控件具有极高的可配置性和可扩展性。当需要在 Windows 窗体应用程序中显示表格数据时,首先考虑使用 DataGridView 控件。若要以小型网格显示只读值,或者若要使用户能够编辑具有数百万条记录的表,DataGridView 控件可以提供方便地进行编程以及有效地利用内存的解决方案。通过选择一些属性,可以轻松地自定义 DataGridView 控件的外观。
DataGridView 控件提供一种强大而灵活的以表格形式显示数据的方式。可以使用该控件显示小型到大型数据集的只读或可编辑视图。可以采用多种方法对 DataGridView 控件进行扩展,以将自定义行为内置在应用程序中。例如,可以采用编程方式指定自己的排序算法,以及创建自己的单元格类型。DataGridView 控件可以显示数据存储区中的数据行。支持多种类型的数据存储区。数据存储区可以保存简单的非类型化数据(例如一维数组),也可以保存类型化数据(例如 DataSet)。
DataGridView 有两个指导原则。首先,其目标是支持常见任务(如主控 / 详细列表、验证和数据格式设置),而不需要您编写许多代码。更重要的是,设计过程中始终考虑了扩展性,因此您可以集成所需的专用功能,而不必采用低级别的复杂编程。
DataGridView 常用属性:
ColumnCount 获取或设置 DataGridView 中显示的列数
Columns 获取控件中所有列的集合
RowCount 获取或设置 DataGridView 中显示的行数
Rows 获取一个集合,该集合包含 DataGridView 控件中的所有行
CurrentCell 获取当前单元格
CurrentRow 获取包含当前单元格的行
SelectedRows 获取用户选定行的集合
DataSource 获取或设置 DataGridView 所绑定的数据源
DataMember 如果数据源绑定的是数据集,那么这里是数据表的名称
DefaultCellStyle 获取或设置 DataGridView 单元格的默认外观样式
DataGridView 常用事件:
CurrentCellChanged() 当选择单元格时发生
CellContentClick() 当点击某个单元格时发生
DataGridView 可实现的基本功能:
1、自定义列
Customize Cells and Columns in the Windows Forms DataGridView Control by Extending Their Behavior and Appearance
Host Controls in Windows Forms DataGridView Cells
继承 DataGridViewTextBoxCell 类生成新的 Cell 类,然后再继承 DataGridViewColumn 生成新的 Column 类,并指定
CellTemplate 为新的 Cell 类。新生成的 Column 便可以增加到 DataGridView 中去。
2、列宽和行高自动调整的设定:
1) 设定行高和列宽自动调整
// 设定包括 Header 和所有单元格的列宽自动调整
DataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;
// 设定包括 Header 和所有单元格的行高自动调整
DataGridView1.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells;
AutoSizeColumnsMode 属性的设定值枚举请参照 msdn 的 DataGridViewAutoSizeRowsMode 说明。
2)指定列或行自动调整
// 第一列自动调整
DataGridView1.Columns[0].AutoSizeMode = DataGridViewAutoSizeColumnMode.DisplayedCells;
AutoSizeMode 设定为 NotSet 时,默认继承的是 DataGridView.AutoSizeColumnsMode 属性。
3) 设定列头的高度和行头的宽度自动调整
// 设定列头的宽度可以自由调整
DataGridView1.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
// 设定行头的宽度可以自由调整
DataGridView1.RowHeadersWidthSizeMode = DataGridViewRowHeadersWidthSizeMode.AutoSizeToAllHeaders;
4)随时自动调整
a,临时的,让列宽自动调整,这和指定 AutoSizeColumnsMode 属性一样。
// 让 DataGridView1 的所有列宽自动调整一下。
DataGridView1.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells);
// 让 DataGridView1 的第一列的列宽自动调整一下。
DataGridView1.AutoResizeColumn(0, DataGridViewAutoSizeColumnMode.AllCells);
上 面调用的 AutoResizeColumns 和 AutoResizeColumn 当指定的是 DataGridViewAutoSizeColumnMode.AllCells 的时候,参数可以省略。即:DataGridView1.AutoResizeColumn(0) 和 DataGridView1.AutoResizeColumns()
b,临时的,让行高自动调整
// 让 DataGridView1 的所有行高自动调整一下。
DataGridView1.AutoResizeRows(DataGridViewAutoSizeRowsMode.AllCells);
// 让 DataGridView1 的第一行的行高自动调整一下。
DataGridView1.AutoResizeRow(0, DataGridViewAutoSizeRowMode.AllCells);
上 面调用的 AutoResizeRows 和 AutoResizeRow 当指定的是 DataGridViewAutoSizeRowMode.AllCells 的时候,参数可以省略。即:DataGridView1.AutoResizeRow (0) 和 DataGridView1.AutoResizeRows()
c,临时的,让行头和列头自动调整
关于性能:通过 AutoSizeColumnsMode 或者 AutoSizeRowsMode 属性所指定的单元格进行自动调整时,如果调整次数过于多那么将可能导致性能下降,尤其是在行和列数比较多的情况下。在这时用 DisplayedCells 代替 AllCells 能减少非所见的单元格的调整,从而提高性能。
// 列头高度自动调整
DataGridView1.AutoResizeColumnHeadersHeight();
// 行头宽度自动调整
DataGridView1.AutoResizeRowHeadersWidth(DataGridViewRowHeadersWidthSizeMode.AutoSizeToAllHeaders);
5)单元格自动适应窗体的宽度
Programmatically Resize Cells to Fit Content in the Windows Forms DataGridView Control
例:
DataGridView.AutoSizeColumns(DataGridViewAutoSizeColumnCriteria.HeaderAndDisplayedRows);
DataGridView.AutoSizeColumn(DataGridViewAutoSizeColumnCriteria.HeaderOnly,2, false);
DataGridView.AutoSizeRow(DataGridViewAutoSizeRowCriteria.Columns,2, false);
DataGridView.AutoSizeRows(DataGridViewAutoSizeRowCriteria.HeaderAndColumns,0, dataGridView1.Rows.Count, false);
3、可以绑定并显示对象
Bind Objects to Windows Forms DataGridView Controls
4、单元格的边框、网格线样式的设定
1) DataGridView 的边框线样式的设定
DataGridView 的边框线的样式是通过 DataGridView.BorderStyle 属性来设定的。BorderStyle 属性设定值是一个
BorderStyle 枚举:FixedSingle(单线,默认)、Fixed3D、None。
2) 单元格的边框线样式的设定
单元格的边框线的样式是通过 DataGridView.CellBorderStyle 属性来设定的。CellBorderStyle 属性设定值是
DataGridViewCellBorderStyle 枚举。(详细参见 MSDN)
另外,通过 DataGridView.ColumnHeadersBorderStyle 和 RowHeadersBorderStyle 属性可以修改 DataGridView 的头部的单元格边框线样式。属性设定值是 DataGridViewHeaderBorderStyle 枚举。(详细参见 MSDN)
3)单元格的边框颜色的设定
单元格的边框线的颜色可以通过 DataGridView.GridColor 属性来设定的。默认是 ControlDarkDark。但是只有在 CellBorderStyle 被设定为 Single、SingleHorizontal、SingleVertical 的条件下才能改变其边框线的颜色。同样,ColumnHeadersBorderStyle 以及 RowHeadersBorderStyle 只有在被设定为 Single 时,才能改变颜色。
4)单元格的上下左右的边框线式样的单独设定
CellBorderStyle 只能设定单元格全部边框线的式样。要单独改变单元格某一边边框式样的话,需要用到 DataGridView.AdvancedCellBorderStyle 属性。
同样,设定行头单元格的属性是:AdvancedRowHeadersBorderStyle,设定列头单元格属性是:AdvancedColumnHeadersBorderStyle。
5、动态改变列是否显示,和动态改变列的显示顺序
Change the Order of the Columns in the Windows Forms DataGridView Control
例:
customersDataGridView.Columns[“CustomerID”].Visible = false;
customersDataGridView.Columns[“ContactName”].DisplayIndex = 0;
customersDataGridView.Columns[“ContactTitle”].DisplayIndex = 1;
customersDataGridView.Columns[“City”].DisplayIndex = 2;
customersDataGridView.Columns[“Country”].DisplayIndex = 3;
customersDataGridView.Columns[“CompanyName”].DisplayIndex = 4;
设定 DataGridView 的 AllowUserToOrderColumns 为 True 的时候,用户可以自由调整列的顺序。
当用户改变列的顺序的时候,其本身的 Index 不会改变,但是 DisplayIndex 改变了。也可以通过程序改变 DisplayIndex 来改变列的顺序。列顺序发生改变时会引发 ColumnDisplayIndexChanged 事件:
// DataGridView1 的 ColumnDisplayIndexChanged 事件处理方法
private void DataGridView1_ColumnDisplayIndexChanged(object sender, DataGridViewColumnEventArgs e)
{
Console.WriteLine(“{0} 的位置改变到 {1} “,e.Column.Name, e.Column.DisplayIndex);
}
6、在单元格中显示图像
Display Images in Cells of the Windows Forms DataGridView Control
例:
Icon treeIcon = new Icon(this.GetType(), “tree.ico”);
DataGridViewImageColumn iconColumn = new DataGridViewImageColumn ();
iconColumn.Image = treeIcon.ToBitmap();
iconColumn.Name = “Tree”;
iconColumn.HeaderText = “Nice tree”;
dataGridView1.Columns.Insert(2, iconColumn);
7、格式化显示内容:
Format Data in the Windows Forms DataGridView Control
例:
this.dataGridView1.Columns[“UnitPrice”].DefaultCellStyle.Format = “c”;
this.dataGridView1.Columns[“ShipDate”].DefaultCellStyle.Format = “d”;
this.dataGridView1.DefaultCellStyle.NullValue = “no entry”;
this.dataGridView1.DefaultCellStyle.WrapMode = DataGridViewWrapMode.Wrap;
this.dataGridView1.Columns[“CustomerName”].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
8、在拖动列的滚动条时可以将指定的列或行冻结
1)列冻结
DataGridViewColumn.Frozen 属性为 True 时,该列左侧的所有列被固定,横向滚动时固定列不随滚动条滚动而左右移动。这对于重要列固定显示很有用。
// DataGridView1 的左侧 2 列固定
DataGridView1.Columns[1].Frozen = true;
但是,DataGridView.AllowUserToOrderColumns = True 时,固定列不能移动到非固定列,反之亦然。
2)行冻结
DataGridViewRow.Frozen 属性为 True 时,该行上面的所有行被固定,纵向滚动时固定行不随滚动条滚动而上下移动。
// DataGridView1 的上 3 行固定
DataGridView1.Rows[2].Frozen = true;
9、获取已选择的单元格, 行, 列的内容
Get the Selected Cells, Rows, and Columns in the Windows Forms DataGridView Control
例:
1)获取选择的单元格:
private void selectedCellsButton_Click(object sender, System.EventArgs e)
{
Int32 selectedCellCount = dataGridView1.GetCellCount(DataGridViewElementStates.Selected);
if (selectedCellCount > 0)
{
if (dataGridView1.AreAllCellsSelected(true))
{
MessageBox.Show(“All cells are selected”, “Selected Cells”);
}
else
{
System.Text.StringBuilder sb = new System.Text.StringBuilder();
for (int i = 0; i < selectedCellCount; i++)
{
sb.Append(“Row: “);
sb.Append(dataGridView1.SelectedCells[i].RowIndex.ToString());
sb.Append(“, Column: “);
sb.Append(dataGridView1.SelectedCells[i].ColumnIndex.ToString());
sb.Append(Environment.NewLine);
}
sb.Append(“Total: ” + selectedCellCount.ToString());
MessageBox.Show(sb.ToString(), “Selected Cells”);
}
}
}
2)获取选择的行:
private void selectedRowsButton_Click(object sender, System.EventArgs e)
{
Int32 selectedRowCount = dataGridView1.Rows.GetRowCount(DataGridViewElementStates.Selected);
if (selectedRowCount > 0)
{
System.Text.StringBuilder sb = new System.Text.StringBuilder();
for (int i = 0; i < selectedRowCount; i++)
{
sb.Append(“Row: “);
sb.Append(dataGridView1.SelectedRows[i].Index.ToString());
sb.Append(Environment.NewLine);
}
sb.Append(“Total: ” + selectedRowCount.ToString());
MessageBox.Show(sb.ToString(), “Selected Rows”);
}
}
3)获取选择的列:
private void selectedColumnsButton_Click(object sender, System.EventArgs e)
{
Int32 selectedColumnCount = dataGridView1.Columns.GetColumnCount(DataGridViewElementStates.Selected);
if (selectedColumnCount > 0)
{
System.Text.StringBuilder sb = new System.Text.StringBuilder();
for (int i = 0; i < selectedColumnCount; i++)
{
sb.Append(“Column: “);
sb.Append(dataGridView1.SelectedColumns[i].Index.ToString());
sb.Append(Environment.NewLine);
}
sb.Append(“Total: ” + selectedColumnCount.ToString());
MessageBox.Show(sb.ToString(), “Selected Columns”);
}
}
10、在录入出现错误时,显示提示信息
Handle Errors that Occur During Data Entry in the Windows Forms DataGridView Control
例:
private void dataGridView1_DataError(object sender,DataGridViewDataErrorEventArgs e)
{
// If the data source raises an exception when a cell value is
// commited, display an error message.
if (e.Exception != null && e.Context == DataGridViewDataErrorContext.Commit)
{
MessageBox.Show(“CustomerID value must be unique.”);
}
}
11、大数据量显示采用 Virtual Mode
Implement Virtual Mode in the Windows Forms DataGridView Control
12、设定单元格只读:
1)使用 ReadOnly 属性
// 设置 DataGridView1 内所有单元格都为只读。此时,用户的新增行操作和删除行操作也被屏蔽了。
DataGridView1.ReadOnly = true;
//DataGridView 内某个或者某些单元格不可编辑
// 设置 DataGridView1 的第 2 列整列单元格为只读
DataGridView1.Columns[1].ReadOnly = true;
// 设置 DataGridView1 的第 3 行整行单元格为只读
DataGridView1.Rows[2].ReadOnly = true;
// 设置 DataGridView1 的 [0,0] 单元格为只读
DataGridView1[0,0].ReadOnly = true;
2)使用 EditMode 属性
DataGridView.EditMode 属性被设置为 DataGridViewEditMode.EditProgrammatically 时,用户就不能手动编辑单元格的内容了。但是可以通过程序,调用 DataGridView.BeginEdit 方法,使单元格进入编辑模式进行编辑。
DataGridView1.EditMode = DataGridViewEditMode.EditProgrammatically;// 不可编辑
自定义设定光标进入单元格是否可编辑(编辑模式)
DataGridView1.EditMode = DataGridViewEditMode.EditOnEnter;// 可编辑
3)根据条件设定单元格的不可编辑状态
当一个一个的通过单元格坐标设定单元格 ReadOnly 属性的方法太麻烦的时候,你可以通过 CellBeginEdit 事件来取消单元格的编辑。
// CellBeginEdit 事件处理方法
private void DataGridView1_CellBeginEdit(object sender,
DataGridViewCellCancelEventArgs e)
{
DataGridView dgv = (DataGridView)sender;
// 是否可以进行编辑的条件检查
if (dgv.Columns[e.ColumnIndex].Name == “Column1” && !(bool)dgv[“Column2”, e.RowIndex].Value)
{
// 取消编辑
e.Cancel = true;
}
}
13、移去自动生成的列
Remove Autogenerated Columns from a Windows Forms DataGridView Control
例:
dataGridView1.AutoGenerateColumns = true;
dataGridView1.DataSource = customerDataSet;
dataGridView1.Columns.Remove (“Fax”);
或:
dataGridView1.Columns[“CustomerID”].Visible = false;
14、自定义选择模式(单选,多选,全选……)
Set the Selection Mode of the Windows Forms DataGridView Control
例:
this.dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
this.dataGridView1.MultiSelect = false;
15、不显示最下面的新行
通常 DataGridView 的最下面一行是用户新追加的行(行头显示 *)。如果不想让用户新追加行即不想显示该新行,可以将 DataGridView 对象的 AllowUserToAddRows 属性设置为 False。但是,可以通过程序:DataGridViewRowCollection.Add 为 DataGridView 追加新行。补足:如果 DataGridView 的 DataSource 绑定的是 DataView, 还可以通过设置 DataView.AllowAdd 属性为 False 来达到同样的效果。
// 设置用户不能手动给 DataGridView1 添加新行
DataGridView1.AllowUserToAddRows = false;
16、为新增行指定默认值
需要指定新加行的默认值的时候,可以在 DataGridView.DefaultValuesNeeded 事件里处理。在该事件中处理除了可以设定默认值以外,还可以指定某些特定的单元格的 ReadOnly 属性等。
// DefaultValuesNeeded 事件处理方法
private void DataGridView1_DefaultValuesNeeded(object sender,DataGridViewRowEventArgs e)
{
// 设定单元格的默认值
e.Row.Cells[“Column1”].Value = 0;
e.Row.Cells[“Column2”].Value = “-“;
}
例:
private void dataGridView1_DefaultValuesNeeded(object sender, System.Windows.Forms.DataGridViewRowEventArgs e)
{
e.Row.Cells[“Region”].Value = “WA”;
e.Row.Cells[“City”].Value = “Redmond”;
e.Row.Cells[“PostalCode”].Value = “98052-6399”;
e.Row.Cells[“Region”].Value = “NA”;
e.Row.Cells[“Country”].Value = “USA”;
e.Row.Cells[“CustomerID”].Value = NewCustomerId();
}
17、数据验证
Validate Data in the Windows Forms DataGridView Control
例:
private void dataGridView1_CellValidating(object sender,DataGridViewCellValidatingEventArgs e)
{
// Validate the CompanyName entry by disallowing empty strings.
if (dataGridView1.Columns[e.ColumnIndex].Name == “CompanyName”)
{
if (e.FormattedValue.ToString() == String.Empty)
{
dataGridView1.Rows[e.RowIndex].ErrorText = “Company Name must not be empty”;
e.Cancel = true;
}
}
}
18、数据提交到 dataset 中
DataSet ds = new DataSet(“MyDataSet”);
ds.Tables[biaom.Trim()].Rows.Clear();
try
{
for (int i = 0; i < dataGridView1.Rows.Count – 1; i++)
{
DataTable dt = ds.Tables[biaom.Trim()];
DataRow myrow = ds.Tables[biaom.Trim()].NewRow();
for (int j = 0; j < dataGridView1.Columns.Count; j++)
{
myrow[j] = Convert.ToString(dataGridView1.Rows[i].Cells[j].Value);
}
ds.Tables[biaom.Trim()].Rows.Add(myrow);
}
}
catch (Exception)
{
MessageBox.Show(“ 输入类型错误!”);
return;
}
19、DataGridView 取得或者修改当前单元格的内容:
当前单元格指的是 DataGridView 焦点所在的单元格,它可以通过 DataGridView 对象的 CurrentCell 属性取得。如果当前单元格不存在的时候,返回 Nothing(C# 是 null)
// 取得当前单元格内容
Console.WriteLine(DataGridView1.CurrentCell.Value);
// 取得当前单元格的列 Index
Console.WriteLine(DataGridView1.CurrentCell.ColumnIndex);
// 取得当前单元格的行 Index
Console.WriteLine(DataGridView1.CurrentCell.RowIndex);
另外,使用 DataGridView.CurrentCellAddress 属性(而不是直接访问单元格)来确定单元格所在的行:DataGridView.CurrentCellAddress.Y 和列:DataGridView.CurrentCellAddress.X。这对于避免取消共享行的共享非常有用。
当前的单元格可以通过设定 DataGridView 对象的 CurrentCell 来改变。可以通过 CurrentCell 来设定 DataGridView 的激活单元格。将 CurrentCell 设为 Nothing(null) 可以取消激活的单元格。
// 设定 (0, 0) 为当前单元格
DataGridView1.CurrentCell = DataGridView1[0, 0];
在整行选中模式开启时,你也可以通过 CurrentCell 来设定选定行。
/// <summary>
/// 向下遍历
/// </summary>
/// <param name=”sender”></param>
/// <param name=”e”></param>
private void button4_Click(object sender, EventArgs e)
{
int row = this.dataGridView1.CurrentRow.Index + 1;
if (row > this.dataGridView1.RowCount – 1)
row = 0;
this.dataGridView1.CurrentCell = this.dataGridView1[0, row];
}
/// <summary>
/// 向上遍历
/// </summary>
/// <param name=”sender”></param>
/// <param name=”e”></param>
private void button5_Click(object sender, EventArgs e)
{
int row = this.dataGridView1.CurrentRow.Index – 1;
if (row < 0)
row = this.dataGridView1.RowCount – 1;
this.dataGridView1.CurrentCell = this.dataGridView1[0, row];
}
* 注意: this.dataGridView 的索引器的参数是: columnIndex, rowIndex 或是 columnName, rowIndex。这与习惯不同。
20、判断新增行
DataGridView 的 AllowUserToAddRows 属性为 True 时也就是允许用户追加新行的场合下,DataGridView 的最后一行就是新追加的行(* 行)。使用 DataGridViewRow.IsNewRow 属性可以判断哪一行是新追加的行。另外,通过 DataGridView.NewRowIndex 可以获取新行的行序列号。在没有新行的时候,NewRowIndex = -1。
21、自定义行的用户删除操作
1)无条件的限制行删除操作。
默认时,DataGridView 是允许用户进行行的删除操作的。如果设置 DataGridView 对象的 AllowUserToDeleteRows 属性为 False 时,用户的行删除操作就被禁止了。
但是,通过 DataGridViewRowCollection.Remove 还是可以进行行的删除。
补足:如果 DataGridView 绑定的是 DataView 的话,通过 DataView.AllowDelete 也可以控制行的删除。
// 禁止 DataGridView1 的行删除操作。
DataGridView1.AllowUserToDeleteRows = false;
2)行删除时的条件判断处理。
用户在删除行的时候,将会引发 DataGridView.UserDeletingRow 事件。在这个事件里,可以判断条件并取消删除操作。
// DataGridView1 的 UserDeletingRow 事件
private void DataGridView1_UserDeletingRow(object sender, DataGridViewRowCancelEventArgs e)
{
// 删除前的用户确认。
if (MessageBox.Show(“ 确认要删除该行数据吗?”, “ 删除确认 ”,MessageBoxButtons.OKCancel, MessageBoxIcon.Question) != DialogResult.OK)
{
// 如果不是 OK,则取消。
e.Cancel = true;
}
}
22、行、列的隐藏和删除
1)行、列的隐藏
// DataGridView1 的第一列隐藏
DataGridView1.Columns[0].Visible = false;
// DataGridView1 的第一行隐藏
DataGridView1.Rows[0].Visible = false;
2)行头、列头的隐藏
// 列头隐藏
DataGridView1.ColumnHeadersVisible = false;
// 行头隐藏
DataGridView1.RowHeadersVisible = false;
3)行和列的删除
// 删除名为 ”Column1″ 的列
DataGridView1.Columns.Remove(“Column1”);
// 删除第一列
DataGridView1.Columns.RemoveAt(0);
// 删除第一行
DataGridView1.Rows.RemoveAt(0);
4)删除选中行
foreach (DataGridViewRow r in DataGridView1.SelectedRows)
{
if (!r.IsNewRow)
{
DataGridView1.Rows.Remove(r);
}
}
23、禁止用户调整列或者行的大小(Resize)
1)禁止所有的列或者行的 Resize
// 禁止用户改变 DataGridView1 的所有列的列宽
DataGridView1.AllowUserToResizeColumns = false;
// 禁止用户改变 DataGridView1 の所有行的行高
DataGridView1.AllowUserToResizeRows = false;
但是可以通过 DataGridViewColumn.Width 或者 DataGridViewRow.Height 属性设定列宽和行高。
2)禁止指定行或者列的 Resize
// 禁止用户改变 DataGridView1 的第一列的列宽
DataGridView1.Columns[0].Resizable = DataGridViewTriState.False;
// 禁止用户改变 DataGridView1 的第一行的行宽
DataGridView1.Rows[0].Resizable = DataGridViewTriState.False;
? 关于 NoSet
当 Resizable 属性设为 DataGridViewTriState.NotSet 时,实际上会默认以 DataGridView 的 AllowUserToResizeColumns 和
AllowUserToResizeRows 的属性值进行设定。比如:DataGridView.AllowUserToResizeColumns = False 且 Resizable 是 NoSet 设定时,Resizable = False。判断 Resizable 是否是继承设定了 DataGridView 的 AllowUserToResizeColumns 和 AllowUserToResizeRows 的属性值,可以根据 State 属性判断。如果 State 属性含有 ResizableSet,那么说明没有继承设定。
3)列宽和行高的最小值的设定
// 第一列的最小列宽设定为 100
DataGridView1.Columns[0].MinimumWidth = 100;
// 第一行的最小行高设定为 50
DataGridView1.Rows[0].MinimumHeight = 50;
4) 禁止用户改变行头的宽度以及列头的高度
// 禁止用户改变列头的高度
DataGridView1.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.DisableResizing;
// 禁止用户改变行头的宽度
DataGridView1.RowHeadersWidthSizeMode = DataGridViewRowHeadersWidthSizeMode.EnableResizing;
24、行头列头的单元格
// 改变 DataGridView1 的第一列列头内容
DataGridView1.Columns[0].HeaderCell.Value = “ 第一列 ”;
// 改变 DataGridView1 的第一行行头内容
DataGridView1.Rows[0].HeaderCell.Value = “ 第一行 ”;
// 改变 DataGridView1 的左上头部单元内容
DataGridView1.TopLeftHeaderCell.Value = “ 左上 ”;
另外也可以通过 HeaderText 来改变他们的内容。
// 改变 DataGridView1 的第一列列头内容
DataGridView1.Columns[0].HeaderText = “ 第一列 ”;
25、剪切板的操作
DataGridView.ClipboardCopyMode 属性被设定为 DataGridViewClipboardCopyMode.Disable 以外的情况时,「Ctrl + C」按下的时候,被选择的单元格的内容会拷贝到系统剪切板内。格式有:Text,UnicodeText,Html,CommaSeparatedValue。可以直接粘贴到 Excel 内。
ClipboardCopyMode 还可以设定 Header 部分是否拷贝:EnableAlwaysIncludeHeaderText 拷贝 Header 部分、EnableWithoutHeaderText 则不拷贝。默认是 EnableWithAutoHeaderText,Header 如果选择了的话,就拷贝。
1)编程方式实现剪切板的拷贝
Clipboard.SetDataObject(DataGridView1.GetClipboardContent())
2)DataGridView 的数据粘贴
实现剪切板的拷贝比较容易,但是实现 DataGridView 的直接粘贴就比较难了。「Ctrl + V」按下进行粘贴时,DataGridView 没有提供方法,只能自己实现。
以下,是粘贴时简单的事例代码,将拷贝数据粘贴到以选择单元格开始的区域内。
// 当前单元格是否选择的判断
if (DataGridView1.CurrentCell == null)
return;
int insertRowIndex = DataGridView1.CurrentCell.RowIndex;
// 获取剪切板的内容,并按行分割
string pasteText = Clipboard.GetText();
if (string.IsNullOrEmpty(pasteText))
return;
pasteText = pasteText.Replace(” “, ” “);
pasteText = pasteText.Replace(‘ ‘, ‘ ‘);
pasteText.TrimEnd(new char[] {‘ ‘});
string[] lines = pasteText.Split(‘ ‘);
bool isHeader = true;
foreach (string line in lines)
{
// 是否是列头
if (isHeader)
{
isHeader = false;
continue;
}
// 按 Tab 分割数据
string[] vals = line.Split(‘ ‘);
// 判断列数是否统一
if (vals.Length – 1 != DataGridView1.ColumnCount)
throw new ApplicationException(“ 粘贴的列数不正确。”);
DataGridViewRow row = DataGridView1.Rows[insertRowIndex];
// 行头设定
row.HeaderCell.Value = vals[0];
// 单元格内容设定
for (int i = 0; i < row.Cells.Count; i++)
{
row.Cells[i].Value = vals[i + 1];
}
// DataGridView 的行索引 +1
insertRowIndex++;
}
26、单元格的 ToolTip 的设置
DataGridView.ShowCellToolTips = True 的情况下,单元格的 ToolTip 可以表示出来。对于单元格窄小,无法完全显示的单元格,ToolTip 可以显示必要的信息。
1)设定单元格的 ToolTip 内容
// 设定单元格的 ToolTip 内容
DataGridView1[0, 0].ToolTipText = “ 该单元格的内容不能修改 ”;
// 设定列头的单元格的 ToolTip 内容
DataGridView1.Columns[0].ToolTipText = “ 该列只能输入数字 ”;
// 设定行头的单元格的 ToolTip 内容
DataGridView1.Rows[0].HeaderCell.ToolTipText = “ 该行单元格内容不能修改 ”;
2)CellToolTipTextNeeded 事件
在批量的单元格的 ToolTip 设定的时候,一个一个指定那么设定的效率比较低,这时候可以利用 CellToolTipTextNeeded 事件。当单元格的 ToolTipText 变化的时候也会引发该事件。但是,当 DataGridView 的 DataSource 被指定且 VirualMode=True 的时候,该事件不会被引发。
// CellToolTipTextNeeded 事件处理方法
private void DataGridView1_CellToolTipTextNeeded(object sender,DataGridViewCellToolTipTextNeededEventArgs e)
{
e.ToolTipText = e.ColumnIndex.ToString() + “, ” + e.RowIndex.ToString();
}
27、DataGridView 右键菜单(ContextMenuStrip)
DataGridView, DataGridViewColumn, DataGridViewRow, DataGridViewCell 有 ContextMenuStrip 属性。可以通过设定 ContextMenuStrip 对象来控制 DataGridView 的右键菜单的显示。DataGridViewColumn 的 ContextMenuStrip 属性设定了 除了列头以外的单元格的右键菜单。DataGridViewRow 的 ContextMenuStrip 属性设定了除了行头以外的单元格的右键菜单。DataGridViewCell 的 ContextMenuStrip 属性设定了指定单元格的右键菜单。
// DataGridView 的 ContextMenuStrip 设定
DataGridView1.ContextMenuStrip = this.ContextMenuStrip1;
// 列的 ContextMenuStrip 设定
DataGridView1.Columns[0].ContextMenuStrip = this.ContextMenuStrip2;
// 列头的 ContextMenuStrip 设定
DataGridView1.Columns[0].HeaderCell.ContextMenuStrip = this.ContextMenuStrip2;
// 行的 ContextMenuStrip 设定
DataGridView1.Rows[0].ContextMenuStrip = this.ContextMenuStrip3;
// 单元格的 ContextMenuStrip 设定
DataGridView1[0, 0].ContextMenuStrip = this.ContextMenuStrip4;
对于单元格上的右键菜单的设定,优先顺序是:Cell > Row > Column > DataGridView
? CellContextMenuStripNeeded、RowContextMenuStripNeeded 事件
利用 CellContextMenuStripNeeded 事件可以设定单元格的右键菜单,尤其但需要右键菜单根据单元格值的变化而变化的时候。比起使用循环遍历,使用该事件来设定右键菜单的效率更高。但是,在 DataGridView 使用了 DataSource 绑定而且是 VirtualMode 的时候,该事件将不被引发。
// CellContextMenuStripNeeded 事件处理方法
private void DataGridView1_CellContextMenuStripNeeded(object sender,DataGridViewCellContextMenuStripNeededEventArgs e)
{
DataGridView dgv = (DataGridView)sender;
if (e.RowIndex < 0)
{
// 列头的 ContextMenuStrip 设定
e.ContextMenuStrip = this.ContextMenuStrip1;
}
else if (e.ColumnIndex < 0)
{
// 行头的 ContextMenuStrip 设定
e.ContextMenuStrip = this.ContextMenuStrip2;
}
else if (dgv[e.ColumnIndex, e.RowIndex].Value is int)
{
// 如果单元格值是整数时
e.ContextMenuStrip = this.ContextMenuStrip3;
}
}
同样,可以通过 RowContextMenuStripNeeded 事件来设定行的右键菜单。
// RowContextMenuStripNeeded 事件处理方法
private void DataGridView1_RowContextMenuStripNeeded(object sender,DataGridViewRowContextMenuStripNeededEventArgs e)
{
DataGridView dgv = (DataGridView)sender;
// 当 ”Column1″ 列是 Bool 型且为 True 时、设定其的 ContextMenuStrip
object boolVal = dgv[“Column1”, e.RowIndex].Value;
Console.WriteLine(boolVal);
if (boolVal is bool && (bool)boolVal)
{
e.ContextMenuStrip = this.ContextMenuStrip1;
}
}
CellContextMenuStripNeeded 事件处理方法的参数中、「e.ColumnIndex=-1」表示行头、「e.RowIndex=-1」表示列头。RowContextMenuStripNeeded 则不存在「e.RowIndex=-1」的情况。
28、单元格表示值的自定义
通过 CellFormatting 事件,可以自定义单元格的表示值。(比如:值为 Error 的时候,单元格被设定为红色)
下面的示例:将“Colmn1”列的值改为大写。
//CellFormatting 事件处理方法
private void DataGridView1_CellFormatting(object sender,DataGridViewCellFormattingEventArgs e)
{
DataGridView dgv = (DataGridView)sender;
// 如果单元格是“Column1”列的单元格
if (dgv.Columns[e.ColumnIndex].Name == “Column1” && e.Value is string)
{
// 将单元格值改为大写
string str = e.Value.ToString();
e.Value = str.ToUpper();
// 应用该 Format,Format 完毕。
e.FormattingApplied = true;
}
}
CellFormatting 事件的 DataGridViewCellFormattingEventArgs 对象的 Value 属性一开始保存着未被格式化的值。当 Value 属性被设定表示用的文本之后,把 FormattingApplied 属性做为 True,告知 DataGridView 文本已经格式化完毕。如果不这样做的话,DataGridView 会根据已经设定的 Format,NullValue,DataSourceNullValue,FormatProvider 属性会将 Value 属性会被重新格式化一遍。
29、列中显示选择框控件CheckBox
DataGridViewCheckBoxColumn column1= new DataGridViewCheckBoxColumn();
{
column1.HeaderText = “ 选择框 ”;
column1.Name = “checkbox”;
column1.AutoSizeMode =
DataGridViewAutoSizeColumnMode.DisplayedCells;
column1.FlatStyle = FlatStyle.Standard;
// 显示选择框的三种状态
column1.ThreeState = true;
}
dataGridView1.Columns.Add(column1);
30、单元格添加下拉框
DataGridViewComboBoxColumn dcombo = new DataGridViewComboBoxColumn();
dcombo.Items.Add(“ 中国 ”);
dcombo.Items.Add(“ 美国 ”);
dcombo.Items.Add(“ 德国 ”);
dcombo.Items.Add(“ 日本 ”);
dcombo.Items.Add(“ 英国 ”);
dcombo.Items.Add(“ 法国 ”);
dcombo.Name = “combo”;
// 显示的位置列
// dcombo.DisplayIndex = 1;
dcombo.HeaderText = “ 国家 ”;
// 绑定数据库的值时使用以下属性
//dcombo.DataPropertyName = “danwei”;
dataGridView1.Columns.Add(dcombo);
以上显示的下拉框,选择时需要点击三次,第一次选中单元格,第二次启用编辑,第三次打开下拉框。
如果需要一次点击打开下拉框,可以启用 DataGridView 的事件 CellEnter();
代码如下:
private void dataGridView1_CellEnter(object sender, DataGridViewCellEventArgs e)
{
// 实现单击显示列表框
if (dataGridView1.Columns[e.ColumnIndex] is DataGridViewComboBoxColumn && e.RowIndex != -1)
{
SendKeys.Send(“{F4}”);
}
}
31、单元格显示按钮控件和显示超级链接
同上,只不过使用的类为:DataGridViewButtonColumn dbotton;
相关代码:
1)显示按钮控件
DataGridViewButtonColumn col=new DataGridViewButtonColumn();
col.Name=”Button”;
col.UseColumnTextForButtonValue=true;
col.Text = “ 按钮 ”;
dataGridView1.Columns.Add(col);
触发的事件为:
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
if (dataGridView1.Columns[e.ColumnIndex].Name==”Button”)
{
MessageBox.Show(“ 触发了按钮 ”);
}
}
2)显示超级链接
DataGridViewLinkColumn
连接代码同上。
单元格列显示图像的是:DataGridViewImageColumn
代码如下:
// 显示图像
DataGridViewImageColumn dgvI=new DataGridViewImageColumn();
dgvI.Name=”Image”;
dgvI.ValuesAreIcons=false;
dgvI.Image = new Bitmap(“c://windows//Blue Lace 16.bmp”);
dgvI.ImageLayout=DataGridViewImageCellLayout.Zoom;
dgvI.Description=” 测试的图片 ”;
dataGridView1.Columns.Add(dgvI);
dataGridView1[“Image”, 0].Value = new Bitmap(“c://windows//Blue Lace 16.bmp”);
32、自动添加序号:
动态添加数据的时候,有时候读取数据库的数据 ID 号不是顺序的,这时就需要自己添加自动递增的序号。
private void button4_Click(object sender, EventArgs e)
{
dataGridView1.Columns[0].HeaderText = “ 序号 ”;
//dataGridView1.Columns[0].DataPropertyName = ds.Tables[0].Columns[1].ToString();
dataGridView1.Columns[0].Width = 80;
dataGridView1.Columns[1].HeaderText = “ 单位 ”;
//dataGridView1.Columns[1].DataPropertyName = ds.Tables[0].Columns[0].ToString();
// dataGridView1.Columns[1].Width = 300;
// 自动整理序列号
int coun = dataGridView1.RowCount;
for (int i = 0; i < coun – 1; i++)
{
dataGridView1.Rows[i].Cells[0].Value = i + 1;
dataGridView1.Rows[i].Cells[“danweiid”].Value = i + 1;
}
// 因为第一个列值被修改了,所以后面的列值索引就从 0 开始。所以单位的值应该对应的是第 0 列
dataGridView1.Columns[0].DataPropertyName = ds.Tables[0].Columns[0].ToString();
}
使用 DataGridView 控件,可以显示和编辑来自多种不同类型的数据源的表格数据。
将数据绑定到 DataGridView 控件非常简单和直观,在大多数情况下,只需设置 DataSource 属性即可。在绑定到包含多个列表或表的数据源时,只需将 DataMember 属性设置为指定要绑定的列表或表的字符串即可。可以将许多类型的数据存储区用作数据源,DataGridView 控件支持标准 Windows 窗体数据绑定模型,也可以在没有绑定数据源的情况下操作 DataGridView 控件。
DataGridView 控件具有极高的可配置性和可扩展性。当需要在 Windows 窗体应用程序中显示表格数据时,首先考虑使用 DataGridView 控件。若要以小型网格显示只读值,或者若要使用户能够编辑具有数百万条记录的表,DataGridView 控件可以提供方便地进行编程以及有效地利用内存的解决方案。通过选择一些属性,可以轻松地自定义 DataGridView 控件的外观。
DataGridView 控件提供一种强大而灵活的以表格形式显示数据的方式。可以使用该控件显示小型到大型数据集的只读或可编辑视图。可以采用多种方法对 DataGridView 控件进行扩展,以将自定义行为内置在应用程序中。例如,可以采用编程方式指定自己的排序算法,以及创建自己的单元格类型。DataGridView 控件可以显示数据存储区中的数据行。支持多种类型的数据存储区。数据存储区可以保存简单的非类型化数据(例如一维数组),也可以保存类型化数据(例如 DataSet)。
DataGridView 有两个指导原则。首先,其目标是支持常见任务(如主控 / 详细列表、验证和数据格式设置),而不需要您编写许多代码。更重要的是,设计过程中始终考虑了扩展性,因此您可以集成所需的专用功能,而不必采用低级别的复杂编程。
DataGridView 常用属性:
ColumnCount 获取或设置 DataGridView 中显示的列数
Columns 获取控件中所有列的集合
RowCount 获取或设置 DataGridView 中显示的行数
Rows 获取一个集合,该集合包含 DataGridView 控件中的所有行
CurrentCell 获取当前单元格
CurrentRow 获取包含当前单元格的行
SelectedRows 获取用户选定行的集合
DataSource 获取或设置 DataGridView 所绑定的数据源
DataMember 如果数据源绑定的是数据集,那么这里是数据表的名称
DefaultCellStyle 获取或设置 DataGridView 单元格的默认外观样式
DataGridView 常用事件:
CurrentCellChanged() 当选择单元格时发生
CellContentClick() 当点击某个单元格时发生
DataGridView 可实现的基本功能:
1、自定义列
Customize Cells and Columns in the Windows Forms DataGridView Control by Extending Their Behavior and Appearance
Host Controls in Windows Forms DataGridView Cells
继承 DataGridViewTextBoxCell 类生成新的 Cell 类,然后再继承 DataGridViewColumn 生成新的 Column 类,并指定
CellTemplate 为新的 Cell 类。新生成的 Column 便可以增加到 DataGridView 中去。
2、列宽和行高自动调整的设定:
1) 设定行高和列宽自动调整
// 设定包括 Header 和所有单元格的列宽自动调整
DataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;
// 设定包括 Header 和所有单元格的行高自动调整
DataGridView1.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells;
AutoSizeColumnsMode 属性的设定值枚举请参照 msdn 的 DataGridViewAutoSizeRowsMode 说明。
2)指定列或行自动调整
// 第一列自动调整
DataGridView1.Columns[0].AutoSizeMode = DataGridViewAutoSizeColumnMode.DisplayedCells;
AutoSizeMode 设定为 NotSet 时,默认继承的是 DataGridView.AutoSizeColumnsMode 属性。
3) 设定列头的高度和行头的宽度自动调整
// 设定列头的宽度可以自由调整
DataGridView1.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
// 设定行头的宽度可以自由调整
DataGridView1.RowHeadersWidthSizeMode = DataGridViewRowHeadersWidthSizeMode.AutoSizeToAllHeaders;
4)随时自动调整
a,临时的,让列宽自动调整,这和指定 AutoSizeColumnsMode 属性一样。
// 让 DataGridView1 的所有列宽自动调整一下。
DataGridView1.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells);
// 让 DataGridView1 的第一列的列宽自动调整一下。
DataGridView1.AutoResizeColumn(0, DataGridViewAutoSizeColumnMode.AllCells);
上 面调用的 AutoResizeColumns 和 AutoResizeColumn 当指定的是 DataGridViewAutoSizeColumnMode.AllCells 的时候,参数可以省略。即:DataGridView1.AutoResizeColumn(0) 和 DataGridView1.AutoResizeColumns()
b,临时的,让行高自动调整
// 让 DataGridView1 的所有行高自动调整一下。
DataGridView1.AutoResizeRows(DataGridViewAutoSizeRowsMode.AllCells);
// 让 DataGridView1 的第一行的行高自动调整一下。
DataGridView1.AutoResizeRow(0, DataGridViewAutoSizeRowMode.AllCells);
上 面调用的 AutoResizeRows 和 AutoResizeRow 当指定的是 DataGridViewAutoSizeRowMode.AllCells 的时候,参数可以省略。即:DataGridView1.AutoResizeRow (0) 和 DataGridView1.AutoResizeRows()
c,临时的,让行头和列头自动调整
关于性能:通过 AutoSizeColumnsMode 或者 AutoSizeRowsMode 属性所指定的单元格进行自动调整时,如果调整次数过于多那么将可能导致性能下降,尤其是在行和列数比较多的情况下。在这时用 DisplayedCells 代替 AllCells 能减少非所见的单元格的调整,从而提高性能。
// 列头高度自动调整
DataGridView1.AutoResizeColumnHeadersHeight();
// 行头宽度自动调整
DataGridView1.AutoResizeRowHeadersWidth(DataGridViewRowHeadersWidthSizeMode.AutoSizeToAllHeaders);
5)单元格自动适应窗体的宽度
Programmatically Resize Cells to Fit Content in the Windows Forms DataGridView Control
例:
DataGridView.AutoSizeColumns(DataGridViewAutoSizeColumnCriteria.HeaderAndDisplayedRows);
DataGridView.AutoSizeColumn(DataGridViewAutoSizeColumnCriteria.HeaderOnly,2, false);
DataGridView.AutoSizeRow(DataGridViewAutoSizeRowCriteria.Columns,2, false);
DataGridView.AutoSizeRows(DataGridViewAutoSizeRowCriteria.HeaderAndColumns,0, dataGridView1.Rows.Count, false);
3、可以绑定并显示对象
Bind Objects to Windows Forms DataGridView Controls
4、单元格的边框、网格线样式的设定
1) DataGridView 的边框线样式的设定
DataGridView 的边框线的样式是通过 DataGridView.BorderStyle 属性来设定的。BorderStyle 属性设定值是一个
BorderStyle 枚举:FixedSingle(单线,默认)、Fixed3D、None。
2) 单元格的边框线样式的设定
单元格的边框线的样式是通过 DataGridView.CellBorderStyle 属性来设定的。CellBorderStyle 属性设定值是
DataGridViewCellBorderStyle 枚举。(详细参见 MSDN)
另外,通过 DataGridView.ColumnHeadersBorderStyle 和 RowHeadersBorderStyle 属性可以修改 DataGridView 的头部的单元格边框线样式。属性设定值是 DataGridViewHeaderBorderStyle 枚举。(详细参见 MSDN)
3)单元格的边框颜色的设定
单元格的边框线的颜色可以通过 DataGridView.GridColor 属性来设定的。默认是 ControlDarkDark。但是只有在 CellBorderStyle 被设定为 Single、SingleHorizontal、SingleVertical 的条件下才能改变其边框线的颜色。同样,ColumnHeadersBorderStyle 以及 RowHeadersBorderStyle 只有在被设定为 Single 时,才能改变颜色。
4)单元格的上下左右的边框线式样的单独设定
CellBorderStyle 只能设定单元格全部边框线的式样。要单独改变单元格某一边边框式样的话,需要用到 DataGridView.AdvancedCellBorderStyle 属性。
同样,设定行头单元格的属性是:AdvancedRowHeadersBorderStyle,设定列头单元格属性是:AdvancedColumnHeadersBorderStyle。
5、动态改变列是否显示,和动态改变列的显示顺序
Change the Order of the Columns in the Windows Forms DataGridView Control
例:
customersDataGridView.Columns[“CustomerID”].Visible = false;
customersDataGridView.Columns[“ContactName”].DisplayIndex = 0;
customersDataGridView.Columns[“ContactTitle”].DisplayIndex = 1;
customersDataGridView.Columns[“City”].DisplayIndex = 2;
customersDataGridView.Columns[“Country”].DisplayIndex = 3;
customersDataGridView.Columns[“CompanyName”].DisplayIndex = 4;
设定 DataGridView 的 AllowUserToOrderColumns 为 True 的时候,用户可以自由调整列的顺序。
当用户改变列的顺序的时候,其本身的 Index 不会改变,但是 DisplayIndex 改变了。也可以通过程序改变 DisplayIndex 来改变列的顺序。列顺序发生改变时会引发 ColumnDisplayIndexChanged 事件:
// DataGridView1 的 ColumnDisplayIndexChanged 事件处理方法
private void DataGridView1_ColumnDisplayIndexChanged(object sender, DataGridViewColumnEventArgs e)
{
Console.WriteLine(“{0} 的位置改变到 {1} “,e.Column.Name, e.Column.DisplayIndex);
}
6、在单元格中显示图像
Display Images in Cells of the Windows Forms DataGridView Control
例:
Icon treeIcon = new Icon(this.GetType(), “tree.ico”);
DataGridViewImageColumn iconColumn = new DataGridViewImageColumn ();
iconColumn.Image = treeIcon.ToBitmap();
iconColumn.Name = “Tree”;
iconColumn.HeaderText = “Nice tree”;
dataGridView1.Columns.Insert(2, iconColumn);
7、格式化显示内容:
Format Data in the Windows Forms DataGridView Control
例:
this.dataGridView1.Columns[“UnitPrice”].DefaultCellStyle.Format = “c”;
this.dataGridView1.Columns[“ShipDate”].DefaultCellStyle.Format = “d”;
this.dataGridView1.DefaultCellStyle.NullValue = “no entry”;
this.dataGridView1.DefaultCellStyle.WrapMode = DataGridViewWrapMode.Wrap;
this.dataGridView1.Columns[“CustomerName”].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
8、在拖动列的滚动条时可以将指定的列或行冻结
1)列冻结
DataGridViewColumn.Frozen 属性为 True 时,该列左侧的所有列被固定,横向滚动时固定列不随滚动条滚动而左右移动。这对于重要列固定显示很有用。
// DataGridView1 的左侧 2 列固定
DataGridView1.Columns[1].Frozen = true;
但是,DataGridView.AllowUserToOrderColumns = True 时,固定列不能移动到非固定列,反之亦然。
2)行冻结
DataGridViewRow.Frozen 属性为 True 时,该行上面的所有行被固定,纵向滚动时固定行不随滚动条滚动而上下移动。
// DataGridView1 的上 3 行固定
DataGridView1.Rows[2].Frozen = true;
9、获取已选择的单元格, 行, 列的内容
Get the Selected Cells, Rows, and Columns in the Windows Forms DataGridView Control
例:
1)获取选择的单元格:
private void selectedCellsButton_Click(object sender, System.EventArgs e)
{
Int32 selectedCellCount = dataGridView1.GetCellCount(DataGridViewElementStates.Selected);
if (selectedCellCount > 0)
{
if (dataGridView1.AreAllCellsSelected(true))
{
MessageBox.Show(“All cells are selected”, “Selected Cells”);
}
else
{
System.Text.StringBuilder sb = new System.Text.StringBuilder();
for (int i = 0; i < selectedCellCount; i++)
{
sb.Append(“Row: “);
sb.Append(dataGridView1.SelectedCells[i].RowIndex.ToString());
sb.Append(“, Column: “);
sb.Append(dataGridView1.SelectedCells[i].ColumnIndex.ToString());
sb.Append(Environment.NewLine);
}
sb.Append(“Total: ” + selectedCellCount.ToString());
MessageBox.Show(sb.ToString(), “Selected Cells”);
}
}
}
2)获取选择的行:
private void selectedRowsButton_Click(object sender, System.EventArgs e)
{
Int32 selectedRowCount = dataGridView1.Rows.GetRowCount(DataGridViewElementStates.Selected);
if (selectedRowCount > 0)
{
System.Text.StringBuilder sb = new System.Text.StringBuilder();
for (int i = 0; i < selectedRowCount; i++)
{
sb.Append(“Row: “);
sb.Append(dataGridView1.SelectedRows[i].Index.ToString());
sb.Append(Environment.NewLine);
}
sb.Append(“Total: ” + selectedRowCount.ToString());
MessageBox.Show(sb.ToString(), “Selected Rows”);
}
}
3)获取选择的列:
private void selectedColumnsButton_Click(object sender, System.EventArgs e)
{
Int32 selectedColumnCount = dataGridView1.Columns.GetColumnCount(DataGridViewElementStates.Selected);
if (selectedColumnCount > 0)
{
System.Text.StringBuilder sb = new System.Text.StringBuilder();
for (int i = 0; i < selectedColumnCount; i++)
{
sb.Append(“Column: “);
sb.Append(dataGridView1.SelectedColumns[i].Index.ToString());
sb.Append(Environment.NewLine);
}
sb.Append(“Total: ” + selectedColumnCount.ToString());
MessageBox.Show(sb.ToString(), “Selected Columns”);
}
}
10、在录入出现错误时,显示提示信息
Handle Errors that Occur During Data Entry in the Windows Forms DataGridView Control
例:
private void dataGridView1_DataError(object sender,DataGridViewDataErrorEventArgs e)
{
// If the data source raises an exception when a cell value is
// commited, display an error message.
if (e.Exception != null && e.Context == DataGridViewDataErrorContext.Commit)
{
MessageBox.Show(“CustomerID value must be unique.”);
}
}
11、大数据量显示采用 Virtual Mode
Implement Virtual Mode in the Windows Forms DataGridView Control
12、设定单元格只读:
1)使用 ReadOnly 属性
// 设置 DataGridView1 内所有单元格都为只读。此时,用户的新增行操作和删除行操作也被屏蔽了。
DataGridView1.ReadOnly = true;
//DataGridView 内某个或者某些单元格不可编辑
// 设置 DataGridView1 的第 2 列整列单元格为只读
DataGridView1.Columns[1].ReadOnly = true;
// 设置 DataGridView1 的第 3 行整行单元格为只读
DataGridView1.Rows[2].ReadOnly = true;
// 设置 DataGridView1 的 [0,0] 单元格为只读
DataGridView1[0,0].ReadOnly = true;
2)使用 EditMode 属性
DataGridView.EditMode 属性被设置为 DataGridViewEditMode.EditProgrammatically 时,用户就不能手动编辑单元格的内容了。但是可以通过程序,调用 DataGridView.BeginEdit 方法,使单元格进入编辑模式进行编辑。
DataGridView1.EditMode = DataGridViewEditMode.EditProgrammatically;// 不可编辑
自定义设定光标进入单元格是否可编辑(编辑模式)
DataGridView1.EditMode = DataGridViewEditMode.EditOnEnter;// 可编辑
3)根据条件设定单元格的不可编辑状态
当一个一个的通过单元格坐标设定单元格 ReadOnly 属性的方法太麻烦的时候,你可以通过 CellBeginEdit 事件来取消单元格的编辑。
// CellBeginEdit 事件处理方法
private void DataGridView1_CellBeginEdit(object sender,
DataGridViewCellCancelEventArgs e)
{
DataGridView dgv = (DataGridView)sender;
// 是否可以进行编辑的条件检查
if (dgv.Columns[e.ColumnIndex].Name == “Column1” && !(bool)dgv[“Column2”, e.RowIndex].Value)
{
// 取消编辑
e.Cancel = true;
}
}
13、移去自动生成的列
Remove Autogenerated Columns from a Windows Forms DataGridView Control
例:
dataGridView1.AutoGenerateColumns = true;
dataGridView1.DataSource = customerDataSet;
dataGridView1.Columns.Remove (“Fax”);
或:
dataGridView1.Columns[“CustomerID”].Visible = false;
14、自定义选择模式(单选,多选,全选……)
Set the Selection Mode of the Windows Forms DataGridView Control
例:
this.dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
this.dataGridView1.MultiSelect = false;
15、不显示最下面的新行
通常 DataGridView 的最下面一行是用户新追加的行(行头显示 *)。如果不想让用户新追加行即不想显示该新行,可以将 DataGridView 对象的 AllowUserToAddRows 属性设置为 False。但是,可以通过程序:DataGridViewRowCollection.Add 为 DataGridView 追加新行。补足:如果 DataGridView 的 DataSource 绑定的是 DataView, 还可以通过设置 DataView.AllowAdd 属性为 False 来达到同样的效果。
// 设置用户不能手动给 DataGridView1 添加新行
DataGridView1.AllowUserToAddRows = false;
16、为新增行指定默认值
需要指定新加行的默认值的时候,可以在 DataGridView.DefaultValuesNeeded 事件里处理。在该事件中处理除了可以设定默认值以外,还可以指定某些特定的单元格的 ReadOnly 属性等。
// DefaultValuesNeeded 事件处理方法
private void DataGridView1_DefaultValuesNeeded(object sender,DataGridViewRowEventArgs e)
{
// 设定单元格的默认值
e.Row.Cells[“Column1”].Value = 0;
e.Row.Cells[“Column2”].Value = “-“;
}
例:
private void dataGridView1_DefaultValuesNeeded(object sender, System.Windows.Forms.DataGridViewRowEventArgs e)
{
e.Row.Cells[“Region”].Value = “WA”;
e.Row.Cells[“City”].Value = “Redmond”;
e.Row.Cells[“PostalCode”].Value = “98052-6399”;
e.Row.Cells[“Region”].Value = “NA”;
e.Row.Cells[“Country”].Value = “USA”;
e.Row.Cells[“CustomerID”].Value = NewCustomerId();
}
17、数据验证
Validate Data in the Windows Forms DataGridView Control
例:
private void dataGridView1_CellValidating(object sender,DataGridViewCellValidatingEventArgs e)
{
// Validate the CompanyName entry by disallowing empty strings.
if (dataGridView1.Columns[e.ColumnIndex].Name == “CompanyName”)
{
if (e.FormattedValue.ToString() == String.Empty)
{
dataGridView1.Rows[e.RowIndex].ErrorText = “Company Name must not be empty”;
e.Cancel = true;
}
}
}
18、数据提交到 dataset 中
DataSet ds = new DataSet(“MyDataSet”);
ds.Tables[biaom.Trim()].Rows.Clear();
try
{
for (int i = 0; i < dataGridView1.Rows.Count – 1; i++)
{
DataTable dt = ds.Tables[biaom.Trim()];
DataRow myrow = ds.Tables[biaom.Trim()].NewRow();
for (int j = 0; j < dataGridView1.Columns.Count; j++)
{
myrow[j] = Convert.ToString(dataGridView1.Rows[i].Cells[j].Value);
}
ds.Tables[biaom.Trim()].Rows.Add(myrow);
}
}
catch (Exception)
{
MessageBox.Show(“ 输入类型错误!”);
return;
}
19、DataGridView 取得或者修改当前单元格的内容:
当前单元格指的是 DataGridView 焦点所在的单元格,它可以通过 DataGridView 对象的 CurrentCell 属性取得。如果当前单元格不存在的时候,返回 Nothing(C# 是 null)
// 取得当前单元格内容
Console.WriteLine(DataGridView1.CurrentCell.Value);
// 取得当前单元格的列 Index
Console.WriteLine(DataGridView1.CurrentCell.ColumnIndex);
// 取得当前单元格的行 Index
Console.WriteLine(DataGridView1.CurrentCell.RowIndex);
另外,使用 DataGridView.CurrentCellAddress 属性(而不是直接访问单元格)来确定单元格所在的行:DataGridView.CurrentCellAddress.Y 和列:DataGridView.CurrentCellAddress.X。这对于避免取消共享行的共享非常有用。
当前的单元格可以通过设定 DataGridView 对象的 CurrentCell 来改变。可以通过 CurrentCell 来设定 DataGridView 的激活单元格。将 CurrentCell 设为 Nothing(null) 可以取消激活的单元格。
// 设定 (0, 0) 为当前单元格
DataGridView1.CurrentCell = DataGridView1[0, 0];
在整行选中模式开启时,你也可以通过 CurrentCell 来设定选定行。
/// <summary>
/// 向下遍历
/// </summary>
/// <param name=”sender”></param>
/// <param name=”e”></param>
private void button4_Click(object sender, EventArgs e)
{
int row = this.dataGridView1.CurrentRow.Index + 1;
if (row > this.dataGridView1.RowCount – 1)
row = 0;
this.dataGridView1.CurrentCell = this.dataGridView1[0, row];
}
/// <summary>
/// 向上遍历
/// </summary>
/// <param name=”sender”></param>
/// <param name=”e”></param>
private void button5_Click(object sender, EventArgs e)
{
int row = this.dataGridView1.CurrentRow.Index – 1;
if (row < 0)
row = this.dataGridView1.RowCount – 1;
this.dataGridView1.CurrentCell = this.dataGridView1[0, row];
}
* 注意: this.dataGridView 的索引器的参数是: columnIndex, rowIndex 或是 columnName, rowIndex。这与习惯不同。
20、判断新增行
DataGridView 的 AllowUserToAddRows 属性为 True 时也就是允许用户追加新行的场合下,DataGridView 的最后一行就是新追加的行(* 行)。使用 DataGridViewRow.IsNewRow 属性可以判断哪一行是新追加的行。另外,通过 DataGridView.NewRowIndex 可以获取新行的行序列号。在没有新行的时候,NewRowIndex = -1。
21、自定义行的用户删除操作
1)无条件的限制行删除操作。
默认时,DataGridView 是允许用户进行行的删除操作的。如果设置 DataGridView 对象的 AllowUserToDeleteRows 属性为 False 时,用户的行删除操作就被禁止了。
但是,通过 DataGridViewRowCollection.Remove 还是可以进行行的删除。
补足:如果 DataGridView 绑定的是 DataView 的话,通过 DataView.AllowDelete 也可以控制行的删除。
// 禁止 DataGridView1 的行删除操作。
DataGridView1.AllowUserToDeleteRows = false;
2)行删除时的条件判断处理。
用户在删除行的时候,将会引发 DataGridView.UserDeletingRow 事件。在这个事件里,可以判断条件并取消删除操作。
// DataGridView1 的 UserDeletingRow 事件
private void DataGridView1_UserDeletingRow(object sender, DataGridViewRowCancelEventArgs e)
{
// 删除前的用户确认。
if (MessageBox.Show(“ 确认要删除该行数据吗?”, “ 删除确认 ”,MessageBoxButtons.OKCancel, MessageBoxIcon.Question) != DialogResult.OK)
{
// 如果不是 OK,则取消。
e.Cancel = true;
}
}
22、行、列的隐藏和删除
1)行、列的隐藏
// DataGridView1 的第一列隐藏
DataGridView1.Columns[0].Visible = false;
// DataGridView1 的第一行隐藏
DataGridView1.Rows[0].Visible = false;
2)行头、列头的隐藏
// 列头隐藏
DataGridView1.ColumnHeadersVisible = false;
// 行头隐藏
DataGridView1.RowHeadersVisible = false;
3)行和列的删除
// 删除名为 ”Column1″ 的列
DataGridView1.Columns.Remove(“Column1”);
// 删除第一列
DataGridView1.Columns.RemoveAt(0);
// 删除第一行
DataGridView1.Rows.RemoveAt(0);
4)删除选中行
foreach (DataGridViewRow r in DataGridView1.SelectedRows)
{
if (!r.IsNewRow)
{
DataGridView1.Rows.Remove(r);
}
}
23、禁止用户调整列或者行的大小(Resize)
1)禁止所有的列或者行的 Resize
// 禁止用户改变 DataGridView1 的所有列的列宽
DataGridView1.AllowUserToResizeColumns = false;
// 禁止用户改变 DataGridView1 の所有行的行高
DataGridView1.AllowUserToResizeRows = false;
但是可以通过 DataGridViewColumn.Width 或者 DataGridViewRow.Height 属性设定列宽和行高。
2)禁止指定行或者列的 Resize
// 禁止用户改变 DataGridView1 的第一列的列宽
DataGridView1.Columns[0].Resizable = DataGridViewTriState.False;
// 禁止用户改变 DataGridView1 的第一行的行宽
DataGridView1.Rows[0].Resizable = DataGridViewTriState.False;
? 关于 NoSet
当 Resizable 属性设为 DataGridViewTriState.NotSet 时,实际上会默认以 DataGridView 的 AllowUserToResizeColumns 和
AllowUserToResizeRows 的属性值进行设定。比如:DataGridView.AllowUserToResizeColumns = False 且 Resizable 是 NoSet 设定时,Resizable = False。判断 Resizable 是否是继承设定了 DataGridView 的 AllowUserToResizeColumns 和 AllowUserToResizeRows 的属性值,可以根据 State 属性判断。如果 State 属性含有 ResizableSet,那么说明没有继承设定。
3)列宽和行高的最小值的设定
// 第一列的最小列宽设定为 100
DataGridView1.Columns[0].MinimumWidth = 100;
// 第一行的最小行高设定为 50
DataGridView1.Rows[0].MinimumHeight = 50;
4) 禁止用户改变行头的宽度以及列头的高度
// 禁止用户改变列头的高度
DataGridView1.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.DisableResizing;
// 禁止用户改变行头的宽度
DataGridView1.RowHeadersWidthSizeMode = DataGridViewRowHeadersWidthSizeMode.EnableResizing;
24、行头列头的单元格
// 改变 DataGridView1 的第一列列头内容
DataGridView1.Columns[0].HeaderCell.Value = “ 第一列 ”;
// 改变 DataGridView1 的第一行行头内容
DataGridView1.Rows[0].HeaderCell.Value = “ 第一行 ”;
// 改变 DataGridView1 的左上头部单元内容
DataGridView1.TopLeftHeaderCell.Value = “ 左上 ”;
另外也可以通过 HeaderText 来改变他们的内容。
// 改变 DataGridView1 的第一列列头内容
DataGridView1.Columns[0].HeaderText = “ 第一列 ”;
25、剪切板的操作
DataGridView.ClipboardCopyMode 属性被设定为 DataGridViewClipboardCopyMode.Disable 以外的情况时,「Ctrl + C」按下的时候,被选择的单元格的内容会拷贝到系统剪切板内。格式有:Text,UnicodeText,Html,CommaSeparatedValue。可以直接粘贴到 Excel 内。
ClipboardCopyMode 还可以设定 Header 部分是否拷贝:EnableAlwaysIncludeHeaderText 拷贝 Header 部分、EnableWithoutHeaderText 则不拷贝。默认是 EnableWithAutoHeaderText,Header 如果选择了的话,就拷贝。
1)编程方式实现剪切板的拷贝
Clipboard.SetDataObject(DataGridView1.GetClipboardContent())
2)DataGridView 的数据粘贴
实现剪切板的拷贝比较容易,但是实现 DataGridView 的直接粘贴就比较难了。「Ctrl + V」按下进行粘贴时,DataGridView 没有提供方法,只能自己实现。
以下,是粘贴时简单的事例代码,将拷贝数据粘贴到以选择单元格开始的区域内。
// 当前单元格是否选择的判断
if (DataGridView1.CurrentCell == null)
return;
int insertRowIndex = DataGridView1.CurrentCell.RowIndex;
// 获取剪切板的内容,并按行分割
string pasteText = Clipboard.GetText();
if (string.IsNullOrEmpty(pasteText))
return;
pasteText = pasteText.Replace(” “, ” “);
pasteText = pasteText.Replace(‘ ‘, ‘ ‘);
pasteText.TrimEnd(new char[] {‘ ‘});
string[] lines = pasteText.Split(‘ ‘);
bool isHeader = true;
foreach (string line in lines)
{
// 是否是列头
if (isHeader)
{
isHeader = false;
continue;
}
// 按 Tab 分割数据
string[] vals = line.Split(‘ ‘);
// 判断列数是否统一
if (vals.Length – 1 != DataGridView1.ColumnCount)
throw new ApplicationException(“ 粘贴的列数不正确。”);
DataGridViewRow row = DataGridView1.Rows[insertRowIndex];
// 行头设定
row.HeaderCell.Value = vals[0];
// 单元格内容设定
for (int i = 0; i < row.Cells.Count; i++)
{
row.Cells[i].Value = vals[i + 1];
}
// DataGridView 的行索引 +1
insertRowIndex++;
}
26、单元格的 ToolTip 的设置
DataGridView.ShowCellToolTips = True 的情况下,单元格的 ToolTip 可以表示出来。对于单元格窄小,无法完全显示的单元格,ToolTip 可以显示必要的信息。
1)设定单元格的 ToolTip 内容
// 设定单元格的 ToolTip 内容
DataGridView1[0, 0].ToolTipText = “ 该单元格的内容不能修改 ”;
// 设定列头的单元格的 ToolTip 内容
DataGridView1.Columns[0].ToolTipText = “ 该列只能输入数字 ”;
// 设定行头的单元格的 ToolTip 内容
DataGridView1.Rows[0].HeaderCell.ToolTipText = “ 该行单元格内容不能修改 ”;
2)CellToolTipTextNeeded 事件
在批量的单元格的 ToolTip 设定的时候,一个一个指定那么设定的效率比较低,这时候可以利用 CellToolTipTextNeeded 事件。当单元格的 ToolTipText 变化的时候也会引发该事件。但是,当 DataGridView 的 DataSource 被指定且 VirualMode=True 的时候,该事件不会被引发。
// CellToolTipTextNeeded 事件处理方法
private void DataGridView1_CellToolTipTextNeeded(object sender,DataGridViewCellToolTipTextNeededEventArgs e)
{
e.ToolTipText = e.ColumnIndex.ToString() + “, ” + e.RowIndex.ToString();
}
27、DataGridView 右键菜单(ContextMenuStrip)
DataGridView, DataGridViewColumn, DataGridViewRow, DataGridViewCell 有 ContextMenuStrip 属性。可以通过设定 ContextMenuStrip 对象来控制 DataGridView 的右键菜单的显示。DataGridViewColumn 的 ContextMenuStrip 属性设定了 除了列头以外的单元格的右键菜单。DataGridViewRow 的 ContextMenuStrip 属性设定了除了行头以外的单元格的右键菜单。DataGridViewCell 的 ContextMenuStrip 属性设定了指定单元格的右键菜单。
// DataGridView 的 ContextMenuStrip 设定
DataGridView1.ContextMenuStrip = this.ContextMenuStrip1;
// 列的 ContextMenuStrip 设定
DataGridView1.Columns[0].ContextMenuStrip = this.ContextMenuStrip2;
// 列头的 ContextMenuStrip 设定
DataGridView1.Columns[0].HeaderCell.ContextMenuStrip = this.ContextMenuStrip2;
// 行的 ContextMenuStrip 设定
DataGridView1.Rows[0].ContextMenuStrip = this.ContextMenuStrip3;
// 单元格的 ContextMenuStrip 设定
DataGridView1[0, 0].ContextMenuStrip = this.ContextMenuStrip4;
对于单元格上的右键菜单的设定,优先顺序是:Cell > Row > Column > DataGridView
? CellContextMenuStripNeeded、RowContextMenuStripNeeded 事件
利用 CellContextMenuStripNeeded 事件可以设定单元格的右键菜单,尤其但需要右键菜单根据单元格值的变化而变化的时候。比起使用循环遍历,使用该事件来设定右键菜单的效率更高。但是,在 DataGridView 使用了 DataSource 绑定而且是 VirtualMode 的时候,该事件将不被引发。
// CellContextMenuStripNeeded 事件处理方法
private void DataGridView1_CellContextMenuStripNeeded(object sender,DataGridViewCellContextMenuStripNeededEventArgs e)
{
DataGridView dgv = (DataGridView)sender;
if (e.RowIndex < 0)
{
// 列头的 ContextMenuStrip 设定
e.ContextMenuStrip = this.ContextMenuStrip1;
}
else if (e.ColumnIndex < 0)
{
// 行头的 ContextMenuStrip 设定
e.ContextMenuStrip = this.ContextMenuStrip2;
}
else if (dgv[e.ColumnIndex, e.RowIndex].Value is int)
{
// 如果单元格值是整数时
e.ContextMenuStrip = this.ContextMenuStrip3;
}
}
同样,可以通过 RowContextMenuStripNeeded 事件来设定行的右键菜单。
// RowContextMenuStripNeeded 事件处理方法
private void DataGridView1_RowContextMenuStripNeeded(object sender,DataGridViewRowContextMenuStripNeededEventArgs e)
{
DataGridView dgv = (DataGridView)sender;
// 当 ”Column1″ 列是 Bool 型且为 True 时、设定其的 ContextMenuStrip
object boolVal = dgv[“Column1”, e.RowIndex].Value;
Console.WriteLine(boolVal);
if (boolVal is bool && (bool)boolVal)
{
e.ContextMenuStrip = this.ContextMenuStrip1;
}
}
CellContextMenuStripNeeded 事件处理方法的参数中、「e.ColumnIndex=-1」表示行头、「e.RowIndex=-1」表示列头。RowContextMenuStripNeeded 则不存在「e.RowIndex=-1」的情况。
28、单元格表示值的自定义
通过 CellFormatting 事件,可以自定义单元格的表示值。(比如:值为 Error 的时候,单元格被设定为红色)
下面的示例:将“Colmn1”列的值改为大写。
//CellFormatting 事件处理方法
private void DataGridView1_CellFormatting(object sender,DataGridViewCellFormattingEventArgs e)
{
DataGridView dgv = (DataGridView)sender;
// 如果单元格是“Column1”列的单元格
if (dgv.Columns[e.ColumnIndex].Name == “Column1” && e.Value is string)
{
// 将单元格值改为大写
string str = e.Value.ToString();
e.Value = str.ToUpper();
// 应用该 Format,Format 完毕。
e.FormattingApplied = true;
}
}
CellFormatting 事件的 DataGridViewCellFormattingEventArgs 对象的 Value 属性一开始保存着未被格式化的值。当 Value 属性被设定表示用的文本之后,把 FormattingApplied 属性做为 True,告知 DataGridView 文本已经格式化完毕。如果不这样做的话,DataGridView 会根据已经设定的 Format,NullValue,DataSourceNullValue,FormatProvider 属性会将 Value 属性会被重新格式化一遍。
29、列中显示选择框控件CheckBox
DataGridViewCheckBoxColumn column1= new DataGridViewCheckBoxColumn();
{
column1.HeaderText = “ 选择框 ”;
column1.Name = “checkbox”;
column1.AutoSizeMode =
DataGridViewAutoSizeColumnMode.DisplayedCells;
column1.FlatStyle = FlatStyle.Standard;
// 显示选择框的三种状态
column1.ThreeState = true;
}
dataGridView1.Columns.Add(column1);
30、单元格添加下拉框
DataGridViewComboBoxColumn dcombo = new DataGridViewComboBoxColumn();
dcombo.Items.Add(“ 中国 ”);
dcombo.Items.Add(“ 美国 ”);
dcombo.Items.Add(“ 德国 ”);
dcombo.Items.Add(“ 日本 ”);
dcombo.Items.Add(“ 英国 ”);
dcombo.Items.Add(“ 法国 ”);
dcombo.Name = “combo”;
// 显示的位置列
// dcombo.DisplayIndex = 1;
dcombo.HeaderText = “ 国家 ”;
// 绑定数据库的值时使用以下属性
//dcombo.DataPropertyName = “danwei”;
dataGridView1.Columns.Add(dcombo);
以上显示的下拉框,选择时需要点击三次,第一次选中单元格,第二次启用编辑,第三次打开下拉框。
如果需要一次点击打开下拉框,可以启用 DataGridView 的事件 CellEnter();
代码如下:
private void dataGridView1_CellEnter(object sender, DataGridViewCellEventArgs e)
{
// 实现单击显示列表框
if (dataGridView1.Columns[e.ColumnIndex] is DataGridViewComboBoxColumn && e.RowIndex != -1)
{
SendKeys.Send(“{F4}”);
}
}
31、单元格显示按钮控件和显示超级链接
同上,只不过使用的类为:DataGridViewButtonColumn dbotton;
相关代码:
1)显示按钮控件
DataGridViewButtonColumn col=new DataGridViewButtonColumn();
col.Name=”Button”;
col.UseColumnTextForButtonValue=true;
col.Text = “ 按钮 ”;
dataGridView1.Columns.Add(col);
触发的事件为:
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
if (dataGridView1.Columns[e.ColumnIndex].Name==”Button”)
{
MessageBox.Show(“ 触发了按钮 ”);
}
}
2)显示超级链接
DataGridViewLinkColumn
连接代码同上。
单元格列显示图像的是:DataGridViewImageColumn
代码如下:
// 显示图像
DataGridViewImageColumn dgvI=new DataGridViewImageColumn();
dgvI.Name=”Image”;
dgvI.ValuesAreIcons=false;
dgvI.Image = new Bitmap(“c://windows//Blue Lace 16.bmp”);
dgvI.ImageLayout=DataGridViewImageCellLayout.Zoom;
dgvI.Description=” 测试的图片 ”;
dataGridView1.Columns.Add(dgvI);
dataGridView1[“Image”, 0].Value = new Bitmap(“c://windows//Blue Lace 16.bmp”);
32、自动添加序号:
动态添加数据的时候,有时候读取数据库的数据 ID 号不是顺序的,这时就需要自己添加自动递增的序号。
private void button4_Click(object sender, EventArgs e)
{
dataGridView1.Columns[0].HeaderText = “ 序号 ”;
//dataGridView1.Columns[0].DataPropertyName = ds.Tables[0].Columns[1].ToString();
dataGridView1.Columns[0].Width = 80;
dataGridView1.Columns[1].HeaderText = “ 单位 ”;
//dataGridView1.Columns[1].DataPropertyName = ds.Tables[0].Columns[0].ToString();
// dataGridView1.Columns[1].Width = 300;
// 自动整理序列号
int coun = dataGridView1.RowCount;
for (int i = 0; i < coun – 1; i++)
{
dataGridView1.Rows[i].Cells[0].Value = i + 1;
dataGridView1.Rows[i].Cells[“danweiid”].Value = i + 1;
}
// 因为第一个列值被修改了,所以后面的列值索引就从 0 开始。所以单位的值应该对应的是第 0 列
dataGridView1.Columns[0].DataPropertyName = ds.Tables[0].Columns[0].ToString();
}
正文完