Datagridview简介

来源:互联网 发布:ubuntu 16.04 1080ti 编辑:程序博客网 时间:2024/06/04 19:09

.net2.0 控件 winform Datagridview简介

DataGridView 对象
到目前为止,您已经了解了如何与当前选定的一组行、单元格和列进行交互。DataGridView 提供了两个关键集合,用于处理整个数据集。这两个集合分别是 Columns(DataGridViewColumn 对象的集合)和 Rows(DataGridViewRow 对象的集合,每个对象都引用一组 DataGridViewCell 对象的集合)。图 2 显示了对象模型。

一般而言,您将使用 DataGridViewColumn 对象来配置列显示属性、格式设置及标题文本,而使用 DataGridViewRow 和 DataGridViewCell 对象从绑定的记录中检索实际数据。在 DataGridViewCell 中修改数据时,处理方式与用户编辑的方式相同:引发相应的 DataGridView 更改事件,并且修改底层的 DataTable。

现在您已经了解了 DataGridView 对象模型,因此可以轻松地创建遍历该表的代码。要选择行、列或单元格,只需找到对应的 DataGridViewRow、DataGridViewColumn 或 DataGridViewCell 对象,并将 IsSelected 属性设置为 True。

以下示例以编程方式选择 OrderID 字段的值小于 100 的所有行:

For Each Row As DataGridViewRow In DataGridView1.Rows
If Row.Cells("OrderID").Value < 100 Then
Row.Selected = True
End If
Next

值得一提的是,有几个从 DataGridViewColumn 派生的不同的类。这些类可以控制在单元格中显示和编辑值的方式。.NET 包括五个预先创建的 DataGridView 列类:DataGridViewButtonColumn、DataGridViewCheckBoxColumn、 DataGridViewComboBoxColumn、DataGridViewImageColumn 和 DataGridViewTextBoxColumn。


DataGridView 样式
设计 DataGridView 时面临的挑战之一就是创建一个格式设置系统,该系统要能够足够灵活地应用不同级别的格式设置,而对于非常大的表又要保持高效。从灵活性角度来看,最好的方法是允许开发人员分别配置每个单元格。但是从效率角度来看,这种方法可能是有害的。包含数千行的表中具有好几万个单元格,维护每个单元格的不同格式肯定会浪费很多内存。

为解决此问题,DataGridView 通过 DataGridViewCellStyle 对象来实现多层模型。DataGridViewCellStyle 对象表示单元格的样式,并且包括如颜色、字体、对齐、换行和数据格式等详细信息。您可以创建一个 DataGridViewCellStyle 来指定整个表的默认格式。此外,还可以指定列、行和各个单元格的默认格式。格式设置的越细致、创建的 DataGridViewCellStyle 对象越多,该解决方案的可伸缩性也就越小。但是,如果您主要使用基于列和基于行的格式设置,并且只是偶尔设置各个单元格的格式,则与 DataGrid 相比,DataGridView 不需要太多内存。

DataGridView 应用格式设置时,将遵循以下优先顺序(从最高到最低):

1. DataGridViewCell.Style
2. DataGridViewRow.DefaultCellStyle
3. DataGridView.AlternatingRowsDefaultCellStyle
4. DataGridView.RowsDefaultCellStyle
5. DataGridViewColumn.DefaultCellStyle
6. DataGridView.DefaultCellStyle

重要的是要清楚:样式对象不是以“全有/全无”的方式应用的,DataGridView 会检查每个属性。例如,假设您的单元格使用 DataGridViewCell.Style 属性来应用自定义字体,但没有设置自定义前景色。结果,该字体设置将覆盖任何其他样式对象中的字体信息,但如果层次结构中下一个样式对象的前景色不为空,则将从该对象继承前景色(在这种情况下为 DataGridViewRow.DefaultCellStyle)。

DataGridViewCellStyle 定义了两种格式设置:数据和外观。数据格式设置描述显示数据绑定值之前如何对其进行修改。这种格式设置通常包括使用格式设置字符串将数字或日期值转换为文本。要使用数据格式设置,只需使用 DataGridViewCellStyle.Format 属性设置格式定义或自定义格式字符串即可。

例如,以下代码片段对 UnitCost 字段中的所有数字进行格式设置,以将它们显示为货币值,保留两位小数并加上在区域设置中定义的相应货币符号:

DataGridView1.Columns("UnitCost"). _
DefaultCellStyle.Format = "C"

外观格式设置包括颜色和格式等表面细节。例如,以下代码右对齐 UnitCost 字段、应用粗体并将单元格的背景更改为黄色:

DataGridView1.Columns("UnitCost"). _
DefaultCellStyle.Font = _
New Font(DataGridView.Font, FontStyle.Bold)
DataGridView1.Columns("UnitCost"). _
DefaultCellStyle.Alignment = _
DataGridViewContentAlignment.MiddleRight
DataGridView1.Columns("UnitCost"). _
DefaultCellStyle.BackColor = Color.LightYellow

其他与格式设置相关的属性包括 ForeColor、SelectionForeColor、SelectionBackColor、WrapMode(控制文本在空间允许时是跨越多行还是直接截断)及 NullValue(将替代 Null 值的值)。

DataGridView 还包括一个设计器,用于在设计时配置列样式。只需从“Properties”(属性)窗口中选择“DataGridView Properties”(DataGridView 属性)链接,或者从各种预先创建的样式设置中选择“AutoFormat”(自动套用格式)。


自定义单元格格式
单元格格式设置的第一种方法是设置更高级别的 DataGridView、DataGridViewColumn 和 DataGridViewRow 属性。但是,有时您需要为特定单元格单独设置样式。例如,您可能需要在列中的数据大于或小于某个值时标记该列中的数据。例如,突出显示项目计划列表中已过去的到期日期,或者在销售分析中突出显示负收益率。在这两种情况下,您需要对单独的单元格进行格式设置。

了解 DataGridView 对象模型后,您可能想要遍历特定列中的单元格集合,以寻找要突出显示的值。这种方法是可行的,但不是最好的方法。关键问题是如果用户编辑了数据,或者如果代码更改了绑定的数据源,不会对单元格的突出显示情况进行相应的更新。

幸运的是,DataGridView 针对此目的提供了 CellFormatting 事件。CellFormatting 只在显示单元格值之前引发。通过该事件,可以基于单元格的内容来更新单元格样式。以下示例检查特定的客户并相应地标记单元格:

Private Sub DataGridView1_CellFormatting( _
ByVal sender As System.Object, _
ByVal e As System.Windows.Forms. _
DataGridViewCellFormattingEventArgs) _
Handles DataGridView1.CellFormatting

' 检查该列是否正确。
If DataGridView1.Columns(e.ColumnIndex).Name = _
"CustomerID" Then
' 检查该值是否正确。
If e.Value = "ALFKI" Then
e.CellStyle.ForeColor = Color.Red
e.CellStyle.BackColor = Color.Yellow
End If
End If
End Sub

样式不是影响网格外观的唯一细节。您还可以隐藏列、在不同位置之间移动列,并“冻结”列,使这些列在用户滚动到右端时仍然可见。这些功能都是通过 DataGridViewColumn 类的属性提供的,如下所述:

? DisplayIndex:设置列在 DataGridView 中显示的位置。例如,DisplayIndex 值为 0 的列将自动显示在最左边的列中。如果多个列具有相同的 DisplayIndex,则先显示最先出现在该集合中的列。因此,如果您使用 DisplayIndex 将一列向左移动,则可能还需要设置最左边的列的 DisplayIndex,以将其向右移动。最初,DisplayIndex 与 DataGridView.Columns 集合中 DataGridViewColumn 对象的索引相匹配。

? Frozen:如果为 True,则该列将始终可见并且固定在表的左侧,即使用户为查看其他列而滚动到右侧亦如此。

? HeaderText:设置将在列标题中显示的文本。

? Resizable 和 MinimumWidth:将 Resizable 设置为 False,以防止用户调整列宽;或者将 MinimumWidth 设置为允许的最小像素数目。

? Visible:要隐藏列,请将此属性设置为 False。

 

 

 


DataGridView常用属性


只读属性设定
        datagridview.ReadOnly = True
        行自动追加
        datagridview.AllowUserToAddRows = False

        删除行允许
        datagridview.AllowUserToDeleteRows = False

        行幅设置
        datagridview.AllowUserToResizeRows = False
      datagridview.ColumnHeadersHeightSizeMode =DataGridViewColumnHeadersHeightSizeMode.DisableResizing

        行表示
        datagridview.RowHeadersVisible = False

        行选择模式
        datagridview.SelectionMode = DataGridViewSelectionMode.FullRowSelect

        复数行选择
        datagridview.MultiSelect = True

        选择状态解除
        datagridview.ClearSelection()

        文字设置位置
        datagridview.ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter

        选择后行的颜色
        datagridview.DefaultCellStyle.SelectionBackColor = Color.GreenYellow
        datagridview.DefaultCellStyle.SelectionForeColor = Color.Black

        行幅自动调整
        datagridview.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill

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、自动适应列宽
Programmatically Resize Cells to Fit Content in the Windows Forms DataGridView Control
Samples:
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、可以改变表格线条风格
Change the Border and Gridline Styles in the Windows Forms DataGridView Control
Samples:
this.dataGridView1.GridColor = Color.BlueViolet;
this.dataGridView1.BorderStyle = BorderStyle.Fixed3D;
this.dataGridView1.CellBorderStyle = DataGridViewCellBorderStyle.None;
this.dataGridView1.RowHeadersBorderStyle = DataGridViewHeaderBorderStyle.Single;
this.dataGridView1.ColumnHeadersBorderStyle = DataGridViewHeaderBorderStyle.Single;
5、动态改变列是否显示,和动态改变列的显示顺序
Change the Order of the Columns in the Windows Forms DataGridView Control
Samples:
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;
6、可以在列中显示图像
Display Images in Cells of the Windows Forms DataGridView Control
Samples:
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
Samples:
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、在拖动列的滚动条时可以将指定的列冻结
Freeze Columns in the Windows Forms DataGridView Control
Samples:将指定列及以前的列固定不动
this.dataGridView1.Columns["AddToCartButton"].Frozen = true;
9、获取选择的单元格,行,列
Get the Selected Cells, Rows, and Columns in the Windows Forms DataGridView Control
Samples:
见msdn。
10、显示录入时出现的错误信息
Handle Errors that Occur During Data Entry in the Windows Forms DataGridView Control
Samples:
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、设置指定的列只读
Make Columns in the Windows Forms DataGridView Control Read-Only
Samples:
dataGridView1.Columns["CompanyName"].ReadOnly = true;
13、移去自动生成的列
Remove Autogenerated Columns from a Windows Forms DataGridView Control
Sample:
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
Sample:
this.dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
this.dataGridView1.MultiSelect = false;
15、自定义设定光标进入单元格是否编辑模式(编辑模式)
Specify the Edit Mode for the Windows Forms DataGridView Control
this.dataGridView1.EditMode = DataGridViewEditMode.EditOnEnter;
16、新行指定默认值
Specify Default Values for New Rows in the Windows Forms DataGridView Control
Sample:
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
Samples:
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;
}
}
}
 
1) 行、列的隐藏

[VB.NET]
' DataGridView1的第一列隐藏
DataGridView1.Columns(0).Visible = False
' DataGridView1的第一行隐藏
DataGridView1.Rows(0).Visible = False


2) 行头、列头的隐藏

[VB.NET]
' 列头隐藏
DataGridView1.ColumnHeadersVisible = False
' 行头隐藏
DataGridView1.RowHeadersVisible = False


3) 行和列的删除

[VB.NET]
' 删除名为"Column1"的列
DataGridView1.Columns.Remove("Column1")
' 删除第一列
DataGridView1.Columns.RemoveAt(0)
' 删除第一行
DataGridView1.Rows.RemoveAt(0)


4) 删除选中行

[VB.NET]
For Each r As DataGridViewRow In DataGridView1.SelectedRows
    If Not r.IsNewRow Then
        DataGridView1.Rows.Remove(r)
    End If
Next


⑦ DataGridView 禁止列或者行的Resize:

1) 禁止所有的列或者行的Resize

[VB.NET]
' 禁止用户改变DataGridView1的所有列的列宽
DataGridView1.AllowUserToResizeColumns = False

'禁止用户改变DataGridView1の所有行的行高
DataGridView1.AllowUserToResizeRows = False

 

 

 

 

怎样获取 dataGridView 单元格的值?

由于DataGridView控件和DataGrid控件比有很多不同之处,
当然它要比DataGrid强大的多,通过以前的索引方法将不能直接获得单元格内容,
因为它的返回值是DataGridViewCell类型,而不是DataGrid以前的Object类型,可以通过DataGridViewCell类型value属性获得,value返回的是Object类型,获取当前选择单元格的值的话可以如下:

1.DataGridView.CurrentCell.Value
2.DataGridView[DataGridView.CurrentCell.ColumnIndex,DataGridView.CurrentCell.RowIndex].Value
当然还有其它方法,可以参考msdn

 


From: http://www.37moti.com/article//soft/