Console.WriteLine(DataGridView1.CurrentCell.Value)
Console.WriteLine(DataGridView1.CurrentCell.ColumnIndex)
Console.WriteLine(DataGridView1.CurrentCell.RowIndex)
DataGridView1.CurrentCell = DataGridView1(0, 0)
全部单元格编辑属性
DataGridView1.ReadOnly = True
指定行列单元格编辑属性
DataGridView1.Columns(1).ReadOnly = True
DataGridView1.Rows(2).ReadOnly = True
DataGridView1(0, 0).ReadOnly = True
根据条件判断单元格的编辑属性
下例中column2的值是True的时候,Column1设为可编辑
Private Sub DataGridView1_CellBeginEdit(ByVal sender As Object, _
ByVal e As DataGridViewCellCancelEventArgs) _
Handles DataGridView1.CellBeginEdit
Dim dgv As DataGridView = CType(sender, DataGridView)
If dgv.Columns(e.ColumnIndex).Name = "Column1" AndAlso _
Not CBool(dgv("Column2", e.RowIndex).Value) Then
e.Cancel = True
End If
End Sub
DataGridView1.AllowUserToAddRows = False
If DataGridView1.CurrentRow.IsNewRow Then
Console.WriteLine("現在のセルがある行は、新しい行です。")
Else
Console.WriteLine("現在のセルがある行は、新しい行ではありません。")
End If
DataGridView1.AllowUserToDeleteRows = False
根据条件判断当前行是否要删除
Private Sub DataGridView1_UserDeletingRow(ByVal sender As Object, _
ByVal e As DataGridViewRowCancelEventArgs) _
Handles DataGridView1.UserDeletingRow
If MessageBox.Show("この列を削除しますか?", "削除の確認", _
MessageBoxButtons.OKCancel, MessageBoxIcon.Question) <> Windows.Forms.DialogResult.OK Then
e.Cancel = True
End If
End Sub
行列不表示
DataGridView1.Columns(0).Visible = False
DataGridView1.Rows(0).Visible = False
行列表头部分不表示
DataGridView1.ColumnHeadersVisible = False
DataGridView1.RowHeadersVisible = False
指定行列删除
DataGridView1.Columns.Remove("Column1")
DataGridView1.Columns.RemoveAt(0)
DataGridView1.Rows.RemoveAt(0)
选择的行列删除(多行列)
Dim r As DataGridViewRow
For Each r In DataGridView1.SelectedRows
If Not r.IsNewRow Then
DataGridView1.Rows.Remove(r)
End If
Next r
DataGridView1.AllowUserToResizeColumns = False
DataGridView1.AllowUserToResizeRows = False
指定行列宽度高度设置为不能编辑
DataGridView1.Columns(0).Resizable = DataGridViewTriState.False
DataGridView1.Rows(0).Resizable = DataGridViewTriState.False
列幅行高最小值设定
DataGridView1.Columns(0).MinimumWidth = 100
DataGridView1.Rows(0).MinimumHeight = 50
行列表头部分行高列幅设置为不能编辑
DataGridView1.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.DisableResizing
DataGridView1.RowHeadersWidthSizeMode = DataGridViewRowHeadersWidthSizeMode.EnableResizing
DataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells
DataGridView1.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells
表头部分行高列幅自动调整
DataGridView1.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize
DataGridView1.RowHeadersWidthSizeMode = DataGridViewRowHeadersWidthSizeMode.AutoSizeToAllHeaders
指定列自动调整
DataGridView1.Columns(0).AutoSizeMode = DataGridViewAutoSizeColumnMode.DisplayedCells
列冻结(当前列以及左侧做所有列)
DataGridView1.Columns(1).Frozen = True
行冻结(当前行以及上部所有行)
DataGridView1.Rows(2).Frozen = True
指定单元格冻结(单元格所在行上部分所有行,列左侧所有列)
DataGridView1(0, 0). Frozen = True
DataGridView1.AllowUserToOrderColumns = True
但是如果列冻结的情况下,冻结的部分不能变更到非冻结的部分。
变更后列位置取得
Console.WriteLine(DataGridView1.Columns("Column1").DisplayIndex)
DataGridView1.Columns("Column1").DisplayIndex = 0
复数行选择不可
DataGridView1.MultiSelect = False
单元格选择的时候默认为选择整行
DataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect
Console.WriteLine("選択されているセル")
For Each c As DataGridViewCell In DataGridView1.SelectedCells
Console.WriteLine("{0}, {1}", c.ColumnIndex, c.RowIndex)
Next c
Console.WriteLine("選択されている行")
For Each r As DataGridViewRow In DataGridView1.SelectedRows
Console.WriteLine(r.Index)
Next r
Console.WriteLine("選択されている列")
For Each c As DataGridViewColumn In DataGridView1.SelectedColumns
Console.WriteLine(c.Index)
Next c
指定行、列、单元格取得
DataGridView1(0, 0).Selected = True
DataGridView1.Rows(1).Selected = True
DataGridView1.Columns(2).Selected = True
If Not DataGridView1(0, 0).Displayed AndAlso _
DataGridView1(0, 0).Visible Then
DataGridView1.CurrentCell = DataGridView1(0, 0)
End If
DataGridView1.Columns(0).HeaderCell.Value = "はじめの列"
DataGridView1.Rows(0).HeaderCell.Value = "はじめの行"
DataGridView1.TopLeftHeaderCell.Value = "左上"
更改列Header表示文字列
DataGridView1.Columns(0).HeaderText = "はじめの列"
更改行Header表示文字列
Dim i As Integer
For i = 0 To DataGridView1.Rows.Count - 1
DataGridView1.Rows(i).HeaderCell.Value = i.ToString()
Next i
DataGridView1.AutoResizeRowHeadersWidth(DataGridViewRowHeadersWidthSizeMode.AutoSizeToAllHeaders)
最左上Header单元格文字列
DataGridView1.TopLeftHeaderCell.Value = "/"
拷贝模式设定
DataGridView1.ClipboardCopyMode = DataGridViewClipboardCopyMode.EnableWithoutHeaderText
选中部分拷贝
Clipboard.SetDataObject(DataGridView1.GetClipboardContent())
If DataGridView1.CurrentCell Is Nothing Then
Return
End If
Dim insertRowIndex As Integer = DataGridView1.CurrentCell.RowIndex
Dim pasteText As String = Clipboard.GetText()
If String.IsNullOrEmpty(pasteText) Then
Return
End If
pasteText = pasteText.Replace(vbCrLf, vbLf)
pasteText = pasteText.Replace(vbCr, vbLf)
pasteText.TrimEnd(New Char() {vbLf})
Dim lines As String() = pasteText.Split(vbLf)
Dim isHeader As Boolean = True
For Each line As String In lines
If isHeader Then
isHeader = False
Else
Dim vals As String() = line.Split(ControlChars.Tab)
If vals.Length - 1 <> DataGridView1.ColumnCount Then
Throw New ApplicationException("列数が違います。")
End If
Dim row As DataGridViewRow = DataGridView1.Rows(insertRowIndex)
row.HeaderCell.Value = vals(0)
Dim i As Integer
For i = 0 To row.Cells.Count - 1
row.Cells(i).Value = vals((i + 1))
Next i
insertRowIndex += 1
End If
Next line
DataGridView1(0, 0).ToolTipText = "このセルは変更できません"
DataGridView1.Columns(0).ToolTipText = "この列には数字を入力できます"
DataGridView1.Rows(0).HeaderCell.ToolTipText = "この行のセルは変更できません"
CellToolTipTextNeeded事件,在多个单元格使用相同的ToolTips的时候,可以用该事件,下例为显示当前单元格的行号和列号
Private Sub DataGridView1_CellToolTipTextNeeded(ByVal sender As Object, _
ByVal e As DataGridViewCellToolTipTextNeededEventArgs) _
Handles DataGridView1.CellToolTipTextNeeded
e.ToolTipText = e.ColumnIndex.ToString() + ", " + e.RowIndex.ToString()
End Sub
DataGridView1.ContextMenuStrip = Me.ContextMenuStrip1
DataGridView1.Columns(0).ContextMenuStrip = Me.ContextMenuStrip2
DataGridView1.Columns(0).HeaderCell.ContextMenuStrip = Me.ContextMenuStrip2
DataGridView1.Rows(0).ContextMenuStrip = Me.ContextMenuStrip3
DataGridView1(1, 0).ContextMenuStrip = Me.ContextMenuStrip4
也可以用CellContextMenuStripNeeded、RowContextMenuStripNeeded属性进行定义
Private Sub DataGridView1_CellContextMenuStripNeeded( _
ByVal sender As Object, _
ByVal e As DataGridViewCellContextMenuStripNeededEventArgs) _
Handles DataGridView1.CellContextMenuStripNeeded
Dim dgv As DataGridView = CType(sender, DataGridView)
If e.RowIndex < 0 Then
e.ContextMenuStrip = Me.ContextMenuStrip1
ElseIf e.ColumnIndex < 0 Then
e.ContextMenuStrip = Me.ContextMenuStrip2
ElseIf TypeOf (dgv(e.ColumnIndex, e.RowIndex).Value) Is Integer Then
e.ContextMenuStrip = Me.ContextMenuStrip3
End If
End Sub
DataGridView1.FirstDisplayedScrollingRowIndex = 0
DataGridView1.FirstDisplayedScrollingColumnIndex = 0
DataGridView1.AutoGenerateColumns = False
DataGridView1.DataSource = BindingSource1
Dim textColumn As New DataGridViewTextBoxColumn()
textColumn.DataPropertyName = "Column1"
textColumn.Name = "Column1"
textColumn.HeaderText = "Column1"
DataGridView1.Columns.Add(textColumn)
DataGridView1.BorderStyle = BorderStyle.Fixed3D
单元格上下左右分界线样式设置
DataGridView1.AdvancedCellBorderStyle.Top = DataGridViewAdvancedCellBorderStyle.InsetDouble
DataGridView1.AdvancedCellBorderStyle.Right = DataGridViewAdvancedCellBorderStyle.Inset
DataGridView1.AdvancedCellBorderStyle.Bottom = DataGridViewAdvancedCellBorderStyle.Inset
DataGridView1.AdvancedCellBorderStyle.Left = DataGridViewAdvancedCellBorderStyle.InsetDouble
如下例,当该列是字符串时,自动转换文字大小写
Private Sub DataGridView1_CellFormatting(ByVal sender As Object, _
ByVal e As DataGridViewCellFormattingEventArgs) _
Handles DataGridView1.CellFormatting
Dim dgv As DataGridView = CType(sender, DataGridView)
If dgv.Columns(e.ColumnIndex).Name = "Column1" AndAlso _
TypeOf e.Value Is String Then
Dim str As String = e.Value.ToString()
e.Value = str.ToUpper()
e.FormattingApplied = True
End If
End Sub
行高设置
DataGridView1.RowTemplate.Height = 50
DataGridView1.RowTemplate.MinimumHeight = 50
样式设置
DataGridView1.DefaultCellStyle.BackColor = Color.Yellow
Private Sub DataGridView1_DefaultValuesNeeded(ByVal sender As Object, _
ByVal e As DataGridViewRowEventArgs) _
Handles DataGridView1.DefaultValuesNeeded
e.Row.Cells("Column1").Value = 0
e.Row.Cells("Column2").Value = "-"
End Sub
DataGridView1(0, 0).ErrorText = "セルの値を確認してください。"
DataGridView1.Rows(3).ErrorText = "負の値は入力できません。"
在大量单元格需要错误提示时,也可以用CellErrorTextNeeded、RowErrorTextNeeded事件
Private Sub DataGridView1_CellErrorTextNeeded(ByVal sender As Object, _
ByVal e As DataGridViewCellErrorTextNeededEventArgs) _
Handles DataGridView1.CellErrorTextNeeded
Dim dgv As DataGridView = CType(sender, DataGridView)
Dim cellVal As Object = dgv(e.ColumnIndex, e.RowIndex).Value
If TypeOf cellVal Is Integer AndAlso CInt(cellVal) < 0 Then
e.ErrorText = "負の整数は入力できません。"
End If
End Sub
Private Sub DataGridView1_RowErrorTextNeeded(ByVal sender As Object, _
ByVal e As DataGridViewRowErrorTextNeededEventArgs) _
Handles DataGridView1.RowErrorTextNeeded
Dim dgv As DataGridView = CType(sender, DataGridView)
If dgv("Column1", e.RowIndex).Value Is DBNull.Value AndAlso _
dgv("Column2", e.RowIndex).Value Is DBNull.Value Then
e.ErrorText = _
"少なくともColumn1とColumn2のどちらかには値を入力してください。"
End If
End Sub
Private Sub DataGridView1_CellValidating(ByVal sender As Object, _
ByVal e As DataGridViewCellValidatingEventArgs) _
Handles DataGridView1.CellValidating
Dim dgv As DataGridView = CType(sender, DataGridView)
If dgv.Columns(e.ColumnIndex).Name = "Column1" AndAlso _
e.FormattedValue.ToString() = "" Then
dgv.Rows(e.RowIndex).ErrorText = "値が入力されていません。"
e.Cancel = True
End If
End Sub
Private Sub DataGridView1_CellValidated(ByVal sender As Object, _
ByVal e As DataGridViewCellEventArgs) _
Handles DataGridView1.CellValidated
Dim dgv As DataGridView = CType(sender, DataGridView)
dgv.Rows(e.RowIndex).ErrorText = Nothing
End Sub
Private Sub DataGridView1_DataError(ByVal sender As Object, _
ByVal e As DataGridViewDataErrorEventArgs) _
Handles DataGridView1.DataError
If Not (e.Exception Is Nothing) Then
MessageBox.Show(Me, _
String.Format("({0}, {1}) のセルでエラーが発生しました。" + _
vbCrLf + vbCrLf + "説明: {2}", _
e.ColumnIndex, e.RowIndex, e.Exception.Message), _
"エラーが発生しました", _
MessageBoxButtons.OK, _
MessageBoxIcon.Error)
End If
End Sub
输入错误值时返回原先数据
Private Sub DataGridView1_DataError(ByVal sender As Object, _
ByVal e As DataGridViewDataErrorEventArgs) _
Handles DataGridView1.DataError
e.Cancel = False
End Sub
For Each c As DataGridViewColumn In DataGridView1.Columns
c.SortMode = DataGridViewColumnSortMode.NotSortable
Next c
Private Sub Form1_Load(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles MyBase.Load
Dim c As DataGridViewColumn
For Each c In DataGridView1.Columns
c.SortMode = DataGridViewColumnSortMode.Automatic
Next c
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click
If DataGridView1.CurrentCell Is Nothing Then
Return
End If
Dim sortColumn As DataGridViewColumn = _
DataGridView1.CurrentCell.OwningColumn
Dim sortDirection As System.ComponentModel.ListSortDirection = _
System.ComponentModel.ListSortDirection.Ascending
If Not (DataGridView1.SortedColumn Is Nothing) AndAlso _
DataGridView1.SortedColumn.Equals(sortColumn) Then
sortDirection = IIf(DataGridView1.SortOrder = SortOrder.Ascending, _
System.ComponentModel.ListSortDirection.Descending, _
System.ComponentModel.ListSortDirection.Ascending)
End If
DataGridView1.Sort(sortColumn, sortDirection)
End Sub
Private Sub DataGridView1_ColumnHeaderMouseClick(ByVal sender As Object, _
ByVal e As DataGridViewCellMouseEventArgs) _
Handles DataGridView1.ColumnHeaderMouseClick
Dim clickedColumn As DataGridViewColumn = _
DataGridView1.Columns(e.ColumnIndex)
If clickedColumn.SortMode <> DataGridViewColumnSortMode.Automatic Then
Me.SortRows(clickedColumn, True)
End If
End Sub
Private Sub DataGridView1_RowsAdded(ByVal sender As Object, _
ByVal e As DataGridViewRowsAddedEventArgs) _
Handles DataGridView1.RowsAdded
Me.SortRows(DataGridView1.SortedColumn, False)
End Sub
Private Sub DataGridView1_CellValueChanged(ByVal sender As Object, _
ByVal e As DataGridViewCellEventArgs) _
Handles DataGridView1.CellValueChanged
If Not (DataGridView1.SortedColumn Is Nothing) AndAlso _
e.ColumnIndex = DataGridView1.SortedColumn.Index Then
Me.SortRows(DataGridView1.SortedColumn, False)
End If
End Sub
Private Sub SortRows(ByVal sortColumn As DataGridViewColumn, _
ByVal orderToggle As Boolean)
If sortColumn Is Nothing Then
Return
End If
If sortColumn.SortMode = DataGridViewColumnSortMode.Programmatic AndAlso _
Not (DataGridView1.SortedColumn Is Nothing) AndAlso _
Not DataGridView1.SortedColumn.Equals(sortColumn) Then
DataGridView1.SortedColumn.HeaderCell.SortGlyphDirection = _
SortOrder.None
End If
Dim sortDirection As System.ComponentModel.ListSortDirection
If orderToggle Then
sortDirection = IIf(DataGridView1.SortOrder = SortOrder.Descending, _
System.ComponentModel.ListSortDirection.Ascending, _
System.ComponentModel.ListSortDirection.Descending)
Else
sortDirection = IIf(DataGridView1.SortOrder = SortOrder.Descending, _
System.ComponentModel.ListSortDirection.Descending, _
System.ComponentModel.ListSortDirection.Ascending)
End If
Dim sOrder As SortOrder = _
IIf(sortDirection = System.ComponentModel.ListSortDirection.Ascending, _
SortOrder.Ascending, SortOrder.Descending)
DataGridView1.Sort(sortColumn, sortDirection)
If sortColumn.SortMode = DataGridViewColumnSortMode.Programmatic Then
sortColumn.HeaderCell.SortGlyphDirection = sOrder
End If
End Sub
Dim dt As DataTable = CType(DataGridView1.DataSource, DataTable)
Dim dv As DataView = dt.DefaultView
dv.Sort = "Column1, Column2 ASC"
DataGridView1.Columns("Column1").HeaderCell.SortGlyphDirection = SortOrder.Ascending
DataGridView1.Columns("Column2").HeaderCell.SortGlyphDirection = SortOrder.Ascending
指定行列的样式设定
DataGridView1.Columns(0).DefaultCellStyle.BackColor = Color.Aqua
DataGridView1.Rows(0).DefaultCellStyle.BackColor = Color.LightGray
奇数行样式设定
DataGridView1.AlternatingRowsDefaultCellStyle.BackColor = Color.GreenYellow
行,列表头部的样式设定
DataGridView1.ColumnHeadersDefaultCellStyle.BackColor = Color.Ivory
DataGridView1.RowHeadersDefaultCellStyle.BackColor = Color.Lime
样式的优先顺序
一般单元格的样式优先顺位
表头部的样式优先顺位
下例说明
DataGridView1.Columns(0).DefaultCellStyle.BackColor = Color.Aqua
DataGridView1.RowsDefaultCellStyle.BackColor = Color.Yellow
DataGridView1.AlternatingRowsDefaultCellStyle.BackColor = Color.GreenYellow
DataGridView1.Rows(2).DefaultCellStyle.BackColor = Color.Pink
Console.WriteLine(DataGridView1.Columns(0).DefaultCellStyle.BackColor)
Console.WriteLine(DataGridView1.Columns(0).InheritedStyle.BackColor)
Console.WriteLine(DataGridView1.Rows(0).DefaultCellStyle.BackColor)
Console.WriteLine(DataGridView1.Rows(0).InheritedStyle.BackColor)
Console.WriteLine(DataGridView1.Rows(1).DefaultCellStyle.BackColor)
Console.WriteLine(DataGridView1.Rows(1).InheritedStyle.BackColor)
Console.WriteLine(DataGridView1.Rows(2).DefaultCellStyle.BackColor)
Console.WriteLine(DataGridView1.Rows(2).InheritedStyle.BackColor)
Console.WriteLine(DataGridView1(0, 2).Style.BackColor)
Console.WriteLine(DataGridView1(0, 2).InheritedStyle.BackColor)
复数行列的样式设定
Dim cellStyle As New DataGridViewCellStyle()
cellStyle.BackColor = Color.Yellow
For i As Integer = 0 To DataGridView1.Columns.Count - 1
If i Mod 2 = 0 Then
DataGridView1.Columns(i).DefaultCellStyle = cellStyle
End If
Next i
For i As Integer = 0 To DataGridView1.Columns.Count - 1
If i Mod 2 = 0 Then
DataGridView1.Columns(i).DefaultCellStyle.BackColor = Color.Yellow
End If
Next i
单元格的设定
DataGridView1.Columns("Column1").DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter
表头的设定
DataGridView1.Columns("Column1").HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter
DataGridView1.Columns("Column1").DefaultCellStyle.WrapMode = DataGridViewTriState.True
DataGridView1.Columns("Column1").HeaderCell.Style.WrapMode = DataGridViewTriState.True
DataGridView1.DefaultCellStyle.NullValue = "(指定されていません)"
单元格内NullValue属性设定的值输入,表示单元格内为Null值
DataGridView1.DefaultCellStyle.NullValue = "-"
DataGridView1.DefaultCellStyle.DataSourceNullValue = "X"
DataGridView1.Columns(0).DefaultCellStyle.Format = "c"
DataGridView1.Columns(1).DefaultCellStyle.Format = "c"
DataGridView1.Columns(1).DefaultCellStyle.FormatProvider = New System.Globalization.CultureInfo("en-US")
Format的参数一览(整数)
書式 |
説明 |
値が"123456"の時 |
|
書式なし |
123456 |
C |
通貨 |
/123,456 |
D |
10進数 |
123456 |
E |
指数 |
1.234560E+005 |
F |
固定小数点 |
123456.00 |
G |
一般 |
123456 |
N |
数値 |
123,456.00 |
P |
パーセント |
12,345,600.00% |
R |
ラウンドトリップ |
(エラーが出る) |
X |
16進数 |
1E240 |
0 |
|
123456 |
00000000 |
|
00123456 |
######## |
|
123456 |
#,##0 |
|
123,456 |
%0 |
|
%12345600 |
00.000E0 |
|
12.346E4 |
プラス#;マイナス#;ゼロ |
|
プラス123456 |
iの値は「#」です。 |
|
iの値は「123456」です |
Format的参数一览(小数)
書式 |
説明 |
値が"1.23456789"の時 |
|
書式なし |
1.23456789 |
C |
通貨 |
/1 |
D |
10進数 |
(エラーが出る) |
E |
指数 |
1.234568E+000 |
F |
固定小数点 |
1.23 |
G |
一般 |
1.23456789 |
N |
数値 |
1.23 |
P |
パーセント |
123.46% |
R |
ラウンドトリップ |
1.23456789 |
X |
16進数 |
(エラーが出る) |
00.0000000000 |
|
01.2345678900 |
##.########## |
|
1.23456789 |
#,##0.000 |
|
1.235 |
%0.## |
|
%123.46 |
00.000E0 |
|
12.346E-1 |
プラス#;マイナス#;ゼロ |
|
プラス1.23 |
dの値は「#.##」です。 |
|
dの値は「1.23」です。 |
光标下的单元格颜色自动变换
Private Sub DataGridView1_CellMouseEnter(ByVal sender As Object, _
ByVal e As DataGridViewCellEventArgs) _
Handles DataGridView1.CellMouseEnter
If e.ColumnIndex >= 0 And e.RowIndex >= 0 Then
Dim dgv As DataGridView = CType(sender, DataGridView)
dgv(e.ColumnIndex, e.RowIndex).Style.BackColor = Color.Red
dgv(e.ColumnIndex, e.RowIndex).Style.SelectionBackColor = Color.Red
End If
End Sub
Private Sub DataGridView1_CellMouseLeave(ByVal sender As Object, _
ByVal e As DataGridViewCellEventArgs) _
Handles DataGridView1.CellMouseLeave
If e.ColumnIndex >= 0 And e.RowIndex >= 0 Then
Dim dgv As DataGridView = CType(sender, DataGridView)
dgv(e.ColumnIndex, e.RowIndex).Style.BackColor = Color.Empty
dgv(e.ColumnIndex, e.RowIndex).Style.SelectionBackColor = Color.Empty
End If
End Sub
表头部单元格颜色设定
DataGridView1.ColumnHeadersDefaultCellStyle.BackColor = Color.Yellow
DataGridView1.RowHeadersDefaultCellStyle.BackColor = Color.YellowGreen
DataGridView1.TopLeftHeaderCell.Style.BackColor = Color.Blue
光标下单元格字体设置为粗体
Private defaultCellStyle As DataGridViewCellStyle
Private mouseCellStyle As DataGridViewCellStyle
Private Sub Form1_Load(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles MyBase.Load
Me.defaultCellStyle = New DataGridViewCellStyle()
Me.mouseCellStyle = New DataGridViewCellStyle()
Me.mouseCellStyle.Font = New Font(DataGridView1.Font, _
DataGridView1.Font.Style Or FontStyle.Bold)
End Sub
Private Sub DataGridView1_CellMouseEnter(ByVal sender As Object, _
ByVal e As DataGridViewCellEventArgs) _
Handles DataGridView1.CellMouseEnter
If e.ColumnIndex >= 0 And e.RowIndex >= 0 Then
Dim dgv As DataGridView = CType(sender, DataGridView)
dgv(e.ColumnIndex, e.RowIndex).Style = Me.mouseCellStyle
End If
End Sub
Private Sub DataGridView1_CellMouseLeave(ByVal sender As Object, _
ByVal e As DataGridViewCellEventArgs) _
Handles DataGridView1.CellMouseLeave
If e.ColumnIndex >= 0 And e.RowIndex >= 0 Then
Dim dgv As DataGridView = CType(sender, DataGridView)
dgv(e.ColumnIndex, e.RowIndex).Style = Me.defaultCellStyle
End If
End Sub
单元格负数情况下显示黄色,0的情况下显示红色
Private Sub DataGridView1_CellFormatting(ByVal sender As Object, _
ByVal e As DataGridViewCellFormattingEventArgs) _
Handles DataGridView1.CellFormatting
Dim dgv As DataGridView = CType(sender, DataGridView)
If dgv.Columns(e.ColumnIndex).Name = "Column1" AndAlso _
TypeOf e.Value Is Integer Then
Dim val As Integer = CInt(e.Value)
If val < 0 Then
e.CellStyle.BackColor = Color.Yellow
Else If val = 0 Then
e.CellStyle.BackColor = Color.Red
End If
End If
End Sub
Private Sub DataGridView1_CellPainting(ByVal sender As Object, _
ByVal e As DataGridViewCellPaintingEventArgs) _
Handles DataGridView1.CellPainting
If e.ColumnIndex >= 0 AndAlso e.RowIndex >= 0 AndAlso _
(e.PaintParts And DataGridViewPaintParts.Background) = _
DataGridViewPaintParts.Background Then
Dim bColor1, bColor2 As Color
If (e.PaintParts And DataGridViewPaintParts.SelectionBackground) = _
DataGridViewPaintParts.SelectionBackground AndAlso _
(e.State And DataGridViewElementStates.Selected) = _
DataGridViewElementStates.Selected Then
bColor1 = e.CellStyle.SelectionBackColor
bColor2 = Color.Black
Else
bColor1 = e.CellStyle.BackColor
bColor2 = Color.LemonChiffon
End If
Dim b As New System.Drawing.Drawing2D.LinearGradientBrush( _
e.CellBounds, bColor1, bColor2, _
System.Drawing.Drawing2D.LinearGradientMode.Horizontal)
Try
e.Graphics.FillRectangle(b, e.CellBounds)
Finally
b.Dispose()
End Try
Dim paintParts As DataGridViewPaintParts = _
e.PaintParts And Not DataGridViewPaintParts.Background
e.Paint(e.ClipBounds, paintParts)
e.Handled = True
End If
End Sub
单元格背景显示图像
Private cellBackImage As New Bitmap("C:/back.gif")
Private Sub DataGridView1_CellPainting(ByVal sender As Object, _
ByVal e As DataGridViewCellPaintingEventArgs) _
Handles DataGridView1.CellPainting
If e.ColumnIndex >= 0 AndAlso e.RowIndex >= 0 AndAlso _
(e.PaintParts And DataGridViewPaintParts.Background) = _
DataGridViewPaintParts.Background Then
Dim backParts As DataGridViewPaintParts = _
e.PaintParts And (DataGridViewPaintParts.Background Or _
DataGridViewPaintParts.SelectionBackground)
e.Paint(e.ClipBounds, backParts)
Dim x As Integer = e.CellBounds.X + _
(e.CellBounds.Width - cellBackImage.Width) / 2
Dim y As Integer = e.CellBounds.Y + _
(e.CellBounds.Height - cellBackImage.Height) / 2
e.Graphics.DrawImage(cellBackImage, x, y)
Dim paintParts As DataGridViewPaintParts = _
e.PaintParts And Not backParts
e.Paint(e.ClipBounds, paintParts)
e.Handled = True
End If
End Sub
利用RowPostPaint事件描画
Private Sub DataGridView1_RowPostPaint(ByVal sender As Object, _
ByVal e As DataGridViewRowPostPaintEventArgs) _
Handles DataGridView1.RowPostPaint
Dim dgv As DataGridView = CType(sender, DataGridView)
Dim linePen As Pen
Select Case e.RowIndex Mod 3
Case 0
linePen = Pens.Blue
Case 1
linePen = Pens.Green
Case Else
linePen = Pens.Red
End Select
Dim startX As Integer = IIf(dgv.RowHeadersVisible, dgv.RowHeadersWidth, 0)
Dim startY As Integer = e.RowBounds.Top + e.RowBounds.Height - 1
Dim endX As Integer = startX + _
dgv.Columns.GetColumnsWidth(DataGridViewElementStates.Visible) - _
dgv.HorizontalScrollingOffset
e.Graphics.DrawLine(linePen, startX, startY, endX, startY)
End Sub
利用RowPrePaint事件描画
Private Sub DataGridView1_RowPrePaint(ByVal sender As Object, _
ByVal e As DataGridViewRowPrePaintEventArgs) _
Handles DataGridView1.RowPrePaint
If (e.PaintParts And DataGridViewPaintParts.Background) = _
DataGridViewPaintParts.Background Then
Dim bColor1, bColor2 As Color
If (e.PaintParts And DataGridViewPaintParts.SelectionBackground) = _
DataGridViewPaintParts.SelectionBackground AndAlso _
(e.State And DataGridViewElementStates.Selected) = _
DataGridViewElementStates.Selected Then
bColor1 = e.InheritedRowStyle.SelectionBackColor
bColor2 = Color.Black
Else
bColor1 = e.InheritedRowStyle.BackColor
bColor2 = Color.YellowGreen
End If
Dim dgv As DataGridView = CType(sender, DataGridView)
Dim rectLeft2 As Integer = IIf(dgv.RowHeadersVisible, dgv.RowHeadersWidth, 0)
Dim rectLeft As Integer = rectLeft2 - dgv.HorizontalScrollingOffset
Dim rectWidth As Integer = dgv.Columns.GetColumnsWidth(DataGridViewElementStates.Visible)
Dim rect As New Rectangle(rectLeft, e.RowBounds.Top, rectWidth, e.RowBounds.Height - 1)
Using b As New System.Drawing.Drawing2D.LinearGradientBrush( _
rect, bColor1, bColor2, _
System.Drawing.Drawing2D.LinearGradientMode.Horizontal)
rect.X = rectLeft2
rect.Width -= dgv.HorizontalScrollingOffset
e.Graphics.FillRectangle(b, rect)
End Using
e.PaintHeader(True)
e.PaintParts = e.PaintParts And Not DataGridViewPaintParts.Background
End If
End Sub
Private Sub DataGridView1_ColumnWidthChanged(ByVal sender As Object, _
ByVal e As DataGridViewColumnEventArgs) _
Handles DataGridView1.ColumnWidthChanged
Dim dgv As DataGridView = CType(sender, DataGridView)
dgv.Invalidate()
End Sub
Private Sub DataGridView1_CellPainting(ByVal sender As Object, _
ByVal e As DataGridViewCellPaintingEventArgs) _
Handles DataGridView1.CellPainting
If e.ColumnIndex < 0 And e.RowIndex >= 0 Then
e.Paint(e.ClipBounds, DataGridViewPaintParts.All)
Dim indexRect As Rectangle = e.CellBounds
indexRect.Inflate(-2, -2)
TextRenderer.DrawText(e.Graphics, _
(e.RowIndex + 1).ToString(), _
e.CellStyle.Font, _
indexRect, _
e.CellStyle.ForeColor, _
TextFormatFlags.Right Or TextFormatFlags.VerticalCenter)
e.Handled = True
End If
End Sub
利用RowPostPaint事件描画
Private Sub DataGridView1_RowPostPaint(ByVal sender As Object, _
ByVal e As DataGridViewRowPostPaintEventArgs) _
Handles DataGridView1.RowPostPaint
Dim dgv As DataGridView = CType(sender, DataGridView)
If dgv.RowHeadersVisible Then
Dim rect As New Rectangle(e.RowBounds.Left, e.RowBounds.Top, _
dgv.RowHeadersWidth, e.RowBounds.Height)
rect.Inflate(-2, -2)
TextRenderer.DrawText(e.Graphics, _
(e.RowIndex + 1).ToString(), _
e.InheritedRowStyle.Font, _
rect, _
e.InheritedRowStyle.ForeColor, _
TextFormatFlags.Right Or TextFormatFlags.VerticalCenter)
End If
End Sub
Private Sub DataGridView1_CellPainting(ByVal sender As Object, _
ByVal e As DataGridViewCellPaintingEventArgs) _
Handles DataGridView1.CellPainting
If e.ColumnIndex >= 0 And e.RowIndex >= 0 Then
Dim paintParts As DataGridViewPaintParts = _
e.PaintParts And Not DataGridViewPaintParts.Focus
e.Paint(e.ClipBounds, paintParts)
e.Handled = True
End If
End Sub
利用RowPrePaint事件实现
Private Sub DataGridView1_RowPrePaint(ByVal sender As Object, _
ByVal e As DataGridViewRowPrePaintEventArgs) _
Handles DataGridView1.RowPrePaint
e.PaintParts = e.PaintParts And Not DataGridViewPaintParts.Focus
End Sub
Dim column As New DataGridViewCheckBoxColumn
DataGridView1.Columns.Add(column)
中间状态在内的三种状态表示
Dim column As DataGridViewCheckBoxColumn = CType(DataGridView1.Columns(0), DataGridViewCheckBoxColumn)
column.ThreeState = True
Dim column As New DataGridViewComboBoxColumn()
column.Items.Add("日曜日")
column.Items.Add("月曜日")
column.Items.Add("火曜日")
column.Items.Add("水曜日")
column.Items.Add("木曜日")
column.Items.Add("金曜日")
column.Items.Add("土曜日")
column.DataPropertyName = "Week"
DataGridView1.Columns.Insert(DataGridView1.Columns("Week").Index, column)
DataGridView1.Columns.Remove("Week")
column.Name = "Week"
通过列Data绑定设置ComboBox
Dim weekTable As New DataTable("WeekTable")
weekTable.Columns.Add("Display", GetType(String))
weekTable.Columns.Add("Value", GetType(Integer))
weekTable.Rows.Add("日曜日", 0)
weekTable.Rows.Add("月曜日", 1)
weekTable.Rows.Add("火曜日", 2)
weekTable.Rows.Add("水曜日", 3)
weekTable.Rows.Add("木曜日", 4)
weekTable.Rows.Add("金曜日", 5)
weekTable.Rows.Add("土曜日", 6)
Dim column As New DataGridViewComboBoxColumn()
column.DataPropertyName = "Week"
column.DataSource = weekTable
column.ValueMember = "Value"
column.DisplayMember = "Display"
DataGridView1.Columns.Add(column)
默认状态下,所有下拉框都显示;DisplayStyleForCurrentCellOnly=True的状态下,当前的单元格显示下拉框,其余不显示;还有一种就是光标移动时强调显示。如下图左中右三列。
通常情况下要打开下拉框需要点击目标单元格三次,第一次选中单元格,第二次进入编辑状态,第三次才能打开下拉框
Private Sub DataGridView1_CellEnter(ByVal sender As Object, _
ByVal e As DataGridViewCellEventArgs) _
Handles DataGridView1.CellEnter
Dim dgv As DataGridView = CType(sender, DataGridView)
If dgv.Columns(e.ColumnIndex).Name = "ComboBox" AndAlso _
TypeOf dgv.Columns(e.ColumnIndex) Is DataGridViewComboBoxColumn Then
SendKeys.Send("{F4}")
End If
End Sub
Dim column As New DataGridViewButtonColumn()
column.Name = "Button"
column.UseColumnTextForButtonValue = True
column.Text = "詳細閲覧"
DataGridView1.Columns.Add(column)
按钮按下事件取得
Private Sub DataGridView1_CellContentClick(ByVal sender As Object, _
ByVal e As DataGridViewCellEventArgs) _
Handles DataGridView1.CellContentClick
Dim dgv As DataGridView = CType(sender, DataGridView)
If dgv.Columns(e.ColumnIndex).Name = "Button" Then
MessageBox.Show((e.RowIndex.ToString() + _
"行のボタンがクリックされました。"))
End If
End Sub
Dim column As New DataGridViewLinkColumn()
column.Name = "Link"
column.UseColumnTextForLinkValue = True
column.Text = "詳細閲覧"
column.LinkBehavior = LinkBehavior.HoverUnderline
column.TrackVisitedState = True
DataGridView1.Columns.Add(column)
链接按下事件取得
Private Sub DataGridView1_CellContentClick(ByVal sender As Object, _
ByVal e As DataGridViewCellEventArgs) _