• DataGridView控件用法合集


    DataGridView控件用法合集

    1.当前的单元格属性取得、变更

    Console.WriteLine(DataGridView1.CurrentCell.Value)

    Console.WriteLine(DataGridView1.CurrentCell.ColumnIndex)

    Console.WriteLine(DataGridView1.CurrentCell.RowIndex)

    DataGridView1.CurrentCell = DataGridView1(0, 0)

    2.DataGridView编辑属性

    全部单元格编辑属性

    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

    3.DataGridView最下面一列新追加行非表示

    DataGridView1.AllowUserToAddRows = False

    4.判断当前选中行是否为新追加的行

    If DataGridView1.CurrentRow.IsNewRow Then

        Console.WriteLine("現在のセルがある行は、新しい行です。")

    Else

        Console.WriteLine("現在のセルがある行は、新しい行ではありません。")

    End If

    5. DataGridView删除行可否设定

    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

    6. DataGridView行列不表示和删除

    行列不表示

    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

    7. DataGridView行列宽度高度设置为不能编辑

    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

    8. DataGridView行高列幅自动调整

    DataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells

    DataGridView1.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells

    表头部分行高列幅自动调整

    DataGridView1.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize

    DataGridView1.RowHeadersWidthSizeMode =  DataGridViewRowHeadersWidthSizeMode.AutoSizeToAllHeaders

    指定列自动调整

    DataGridView1.Columns(0).AutoSizeMode = DataGridViewAutoSizeColumnMode.DisplayedCells

    9. DataGridView指定行列冻结

    列冻结(当前列以及左侧做所有列)

    DataGridView1.Columns(1).Frozen = True

    行冻结(当前行以及上部所有行)

    DataGridView1.Rows(2).Frozen = True

    指定单元格冻结(单元格所在行上部分所有行,列左侧所有列)

    DataGridView1(0, 0). Frozen = True

    10. DataGridView列顺序变更可否设定

    DataGridView1.AllowUserToOrderColumns = True

    但是如果列冻结的情况下,冻结的部分不能变更到非冻结的部分。
    变更后列位置取得

    Console.WriteLine(DataGridView1.Columns("Column1").DisplayIndex)

    DataGridView1.Columns("Column1").DisplayIndex = 0

    11. DataGridView行复数选择

    复数行选择不可

    DataGridView1.MultiSelect = False

    单元格选择的时候默认为选择整行

    DataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect

    12. DataGridView选择的行、列、单元格取得

    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

    13. DataGridView指定单元格是否表示

    If Not DataGridView1(0, 0).Displayed AndAlso _

            DataGridView1(0, 0).Visible Then

        DataGridView1.CurrentCell = DataGridView1(0, 0)

    End If

    14. DataGridView表头部单元格取得

    DataGridView1.Columns(0).HeaderCell.Value = "はじめの列"

    DataGridView1.Rows(0).HeaderCell.Value = "はじめの行"

    DataGridView1.TopLeftHeaderCell.Value = "左上"

    15. DataGridView表头部单元格文字列设定

    更改列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 = "/"

    16. DataGridView选择的部分拷贝至剪贴板

    拷贝模式设定

    DataGridView1.ClipboardCopyMode = DataGridViewClipboardCopyMode.EnableWithoutHeaderText

    选中部分拷贝

    Clipboard.SetDataObject(DataGridView1.GetClipboardContent())

    17.DataGridView粘贴

    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

    18. DataGridView单元格上ToolTip表示设定(鼠标移动到相应单元格上时,弹出说明信息)

    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

    19. DataGridView中的ContextMenuStrip属性

    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

    20.指定DataGridView的滚动框位置

    DataGridView1.FirstDisplayedScrollingRowIndex = 0

    DataGridView1.FirstDisplayedScrollingColumnIndex = 0

    21. DataGridView手动追加列

    DataGridView1.AutoGenerateColumns = False

    DataGridView1.DataSource = BindingSource1

    Dim textColumn As New DataGridViewTextBoxColumn()

    textColumn.DataPropertyName = "Column1"

    textColumn.Name = "Column1"

    textColumn.HeaderText = "Column1"

    DataGridView1.Columns.Add(textColumn)

    22. DataGridView全体分界线样式设置

    DataGridView1.BorderStyle = BorderStyle.Fixed3D

    单元格上下左右分界线样式设置

    DataGridView1.AdvancedCellBorderStyle.Top = DataGridViewAdvancedCellBorderStyle.InsetDouble

    DataGridView1.AdvancedCellBorderStyle.Right = DataGridViewAdvancedCellBorderStyle.Inset

    DataGridView1.AdvancedCellBorderStyle.Bottom = DataGridViewAdvancedCellBorderStyle.Inset

    DataGridView1.AdvancedCellBorderStyle.Left = DataGridViewAdvancedCellBorderStyle.InsetDouble

    23.根据DataGridView单元格属性更改显示内容

    如下例,当该列是字符串时,自动转换文字大小写

    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

    24. DataGridView新追加行的行高样式设置

    行高设置

    DataGridView1.RowTemplate.Height = 50

    DataGridView1.RowTemplate.MinimumHeight = 50

    样式设置

    DataGridView1.DefaultCellStyle.BackColor = Color.Yellow

    25. DataGridView新追加行单元格默认值设置

    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

    26. DataGridView单元格数据错误标签表示

    DataGridView1(0, 0).ErrorText = "セルの値を確認してください。"

    DataGridView1.Rows(3).ErrorText = "負の値は入力できません。"

    在大量单元格需要错误提示时,也可以用CellErrorTextNeededRowErrorTextNeeded事件

    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

    27. DataGridView单元格内输入值正确性判断

    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

    28. DataGridView单元格输入错误值事件的捕获

    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

    29. DataGridView行排序(点击列表头自动排序的设置)

    For Each c As DataGridViewColumn In DataGridView1.Columns

        c.SortMode = DataGridViewColumnSortMode.NotSortable

    Next c

    30. DataGridView自动行排序(新追加值也会自动排序)

    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

    31. DataGridView自动行排序禁止情况下的排序

    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

    32. DataGridView指定列指定排序

    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

    33. DataGridView单元格样式设置

    指定行列的样式设定

    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

    样式的优先顺序

          一般单元格的样式优先顺位

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

    表头部的样式优先顺位

    1. DataGridViewCell.Style
    2. DataGridView.RowHeadersDefaultCellStyle
    3. DataGridView.ColumnHeadersDefaultCellStyle
    4. DataGridView.DefaultCellStyle

    下例说明

    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

    34. DataGridView文字表示位置的设定

    单元格的设定

    DataGridView1.Columns("Column1").DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter

    表头的设定

    DataGridView1.Columns("Column1").HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter

    35. DataGridView单元格内文字列换行

    DataGridView1.Columns("Column1").DefaultCellStyle.WrapMode = DataGridViewTriState.True

    DataGridView1.Columns("Column1").HeaderCell.Style.WrapMode = DataGridViewTriState.True

    36. DataGridView单元格DBNull值表示的设定

    DataGridView1.DefaultCellStyle.NullValue = "(指定されていません)"

    单元格内NullValue属性设定的值输入,表示单元格内为Null值

    DataGridView1.DefaultCellStyle.NullValue = "-"

    DataGridView1.DefaultCellStyle.DataSourceNullValue = "X"

    37. DataGridView单元格样式格式化

    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」です。

    38. DataGridView指定单元格颜色设定

    光标下的单元格颜色自动变换

    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

    39. DataGridView单元格文字字体设置

    光标下单元格字体设置为粗体

    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

    40. DataGridView根据单元格值设定单元格样式

    单元格负数情况下显示黄色,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

    41. DataGridView设置单元格背景颜色

    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

    42. DataGridView行样式描画

    利用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

    43. DataGridView显示行号

    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

    44. DataGridView焦点所在单元格焦点框不显示的设定

    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

    45. DataGridView列中显示选择框CheckBox

    Dim column As New DataGridViewCheckBoxColumn

    DataGridView1.Columns.Add(column)

    中间状态在内的三种状态表示

    Dim column As DataGridViewCheckBoxColumn = CType(DataGridView1.Columns(0), DataGridViewCheckBoxColumn)

    column.ThreeState = True

    46. DataGridView中显示下拉框ComboBox

    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的状态下,当前的单元格显示下拉框,其余不显示;还有一种就是光标移动时强调显示。如下图左中右三列。

    47. DataGridView单击打开下拉框

    通常情况下要打开下拉框需要点击目标单元格三次,第一次选中单元格,第二次进入编辑状态,第三次才能打开下拉框

    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

    48. DataGridView中显示按钮

    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

    49. DataGridView中显示链接

    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) _

            Handles DataGridView1.CellContentClick

        Dim dgv As DataGridView = CType(sender, DataGridView)

        If dgv.Columns(e.ColumnIndex).Name = "Link" Then

            MessageBox.Show((e.RowIndex.ToString() + "行のリンクがクリックされました。"))

            Dim cell As DataGridViewLinkCell = _

                CType(dgv(e.ColumnIndex, e.RowIndex), DataGridViewLinkCell)

            cell.LinkVisited = True

        End If

    End Sub

    50. DataGridView中显示图像

    Dim column As New DataGridViewImageColumn()

    column.Name = "Image"

    column.ValuesAreIcons = False

    column.Image = New Bitmap("C:\null.gif")

    column.ImageLayout = DataGridViewImageCellLayout.Zoom

    column.Description = "イメージ"

    DataGridView1.Columns.Add(column)

    DataGridView1("Image", 0).Value = New Bitmap("C:\top.gif") '

    图片属性单元格未设值时红差不显示的设定

    Dim imageColumn As DataGridViewImageColumn = CType(DataGridView1.Columns("Image"), DataGridViewImageColumn)

    imageColumn.DefaultCellStyle.NullValue = Nothing

    51. DataGridView编辑中单元格控件取得

    Private Sub DataGridView1_EditingControlShowing(ByVal sender As Object, _

            ByVal e As DataGridViewEditingControlShowingEventArgs) _

            Handles DataGridView1.EditingControlShowing

        If TypeOf e.Control Is DataGridViewTextBoxEditingControl Then

            Dim dgv As DataGridView = CType(sender, DataGridView)

            Dim tb As DataGridViewTextBoxEditingControl = CType(e.Control, DataGridViewTextBoxEditingControl)

            If dgv.CurrentCell.OwningColumn.Name = "Column1" Then

                tb.ImeMode = Windows.Forms.ImeMode.Disable

            Else

                tb.ImeMode = dgv.ImeMode

            End If

        End If

    End Sub

    其他控件以此类推,比如DataGridViewCheckBoxColumn或者DataGridViewButtonColumn等等。

    52. DataGridView输入自动完成

    Dim autoCompleteSource As New AutoCompleteStringCollection()

    Private Sub DataGridView1_EditingControlShowing( _

            ByVal sender As Object, _

            ByVal e As DataGridViewEditingControlShowingEventArgs) _

            Handles DataGridView1.EditingControlShowing

        Dim dgv As DataGridView = CType(sender, DataGridView)

        If TypeOf e.Control Is TextBox Then

            Dim tb As TextBox = CType(e.Control, TextBox)

            If dgv.CurrentCell.OwningColumn.Name = "Column1" Then

                tb.AutoCompleteMode = AutoCompleteMode.SuggestAppend

                tb.AutoCompleteSource = _

                    Windows.Forms.AutoCompleteSource.CustomSource

                tb.AutoCompleteCustomSource = Me.autoCompleteSource

            Else

                tb.AutoCompleteMode = AutoCompleteMode.None

            End If

        End If

    End Sub

    Private Sub DataGridView1_DataSourceChanged( _

            ByVal sender As Object, ByVal e As EventArgs) _

            Handles DataGridView1.DataSourceChanged

        Dim dgv As DataGridView = CType(sender, DataGridView)

        Me.autoCompleteSource.Clear()

        Dim r As DataGridViewRow

        For Each r In dgv.Rows

            Dim val As String = r.Cells("Column1").Value

            If Not String.IsNullOrEmpty(val) AndAlso _

                    Not Me.autoCompleteSource.Contains(val) Then

                autoCompleteSource.Add(val)

            End If

        Next r

    End Sub

    Private Sub DataGridView1_CellValueChanged(ByVal sender As Object, _

            ByVal e As DataGridViewCellEventArgs) _

            Handles DataGridView1.CellValueChanged

        Dim dgv As DataGridView = CType(sender, DataGridView)

        If dgv.Columns(e.ColumnIndex).Name = "Column1" Then

            Dim val As String = dgv(e.ColumnIndex, e.RowIndex).Value

            If Not String.IsNullOrEmpty(val) AndAlso Not Me.autoCompleteSource.Contains(val) Then

                autoCompleteSource.Add(val)

            End If

        End If

    End Sub

    53. DataGridView单元格编辑时键盘KEY事件取得

    Private Sub DataGridView1_EditingControlShowing(ByVal sender As Object, _

            ByVal e As DataGridViewEditingControlShowingEventArgs) _

            Handles DataGridView1.EditingControlShowing

        If TypeOf e.Control Is DataGridViewTextBoxEditingControl Then

            Dim dgv As DataGridView = CType(sender, DataGridView)

            Dim tb As DataGridViewTextBoxEditingControl = CType(e.Control, DataGridViewTextBoxEditingControl)

            RemoveHandler tb.KeyPress, AddressOf dataGridViewTextBox_KeyPress

            If dgv.CurrentCell.OwningColumn.Name = "Column1" Then

                AddHandler tb.KeyPress, AddressOf dataGridViewTextBox_KeyPress

            End If

        End If

    End Sub

    Private Sub dataGridViewTextBox_KeyPress(ByVal sender As Object, _

            ByVal e As KeyPressEventArgs) _

            Handles DataGridView1.KeyPress

        If e.KeyChar < "0"c Or e.KeyChar > "9"c Then

            e.Handled = True

        End If

    End Sub

    54. DataGridView下拉框(ComboBox)单元格编辑时事件取得

    Private dataGridViewComboBox As DataGridViewComboBoxEditingControl = Nothing

    Private Sub DataGridView1_EditingControlShowing(ByVal sender As Object, _

            ByVal e As DataGridViewEditingControlShowingEventArgs) _

            Handles DataGridView1.EditingControlShowing

        If TypeOf e.Control Is DataGridViewComboBoxEditingControl Then

            Dim dgv As DataGridView = CType(sender, DataGridView)

            If dgv.CurrentCell.OwningColumn.Name = "ComboBox" Then

                Me.dataGridViewComboBox = _

                    CType(e.Control, DataGridViewComboBoxEditingControl)

                AddHandler Me.dataGridViewComboBox.SelectedIndexChanged, _

                    AddressOf dataGridViewComboBox_SelectedIndexChanged

            End If

        End If

    End Sub

    Private Sub DataGridView1_CellEndEdit(ByVal sender As Object, _

            ByVal e As DataGridViewCellEventArgs) _

            Handles DataGridView1.CellEndEdit

        If Not (Me.dataGridViewComboBox Is Nothing) Then

            RemoveHandler Me.dataGridViewComboBox.SelectedIndexChanged, _

                AddressOf dataGridViewComboBox_SelectedIndexChanged

            Me.dataGridViewComboBox = Nothing

        End If

    End Sub

    Private Sub dataGridViewComboBox_SelectedIndexChanged(ByVal sender As Object, _

            ByVal e As EventArgs)

        Dim cb As DataGridViewComboBoxEditingControl = _

            CType(sender, DataGridViewComboBoxEditingControl)

        Console.WriteLine(cb.SelectedItem)

    End Sub

    55. DataGridView下拉框(ComboBox)单元格允许文字输入设定

    Private Sub DataGridView1_EditingControlShowing(ByVal sender As Object, _

            ByVal e As DataGridViewEditingControlShowingEventArgs) _

            Handles DataGridView1.EditingControlShowing

        If TypeOf e.Control Is DataGridViewComboBoxEditingControl Then

            Dim dgv As DataGridView = CType(sender, DataGridView)

            If dgv.CurrentCell.OwningColumn.Name = "ComboBox" Then

                Dim cb As DataGridViewComboBoxEditingControl = CType(e.Control, DataGridViewComboBoxEditingControl)

                cb.DropDownStyle = ComboBoxStyle.DropDown

            End If

        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 = "ComboBox" AndAlso _

            TypeOf dgv.Columns(e.ColumnIndex) Is DataGridViewComboBoxColumn Then

            Dim cbc As DataGridViewComboBoxColumn = CType(dgv.Columns(e.ColumnIndex), DataGridViewComboBoxColumn)

            If Not cbc.Items.Contains(e.FormattedValue) Then

                cbc.Items.Add(e.FormattedValue)

            End If

        End If

    End Sub

    56. DataGridView根据值不同在另一列中显示相应图片

    Public Class DataGridViewErrorIconColumn

        Inherits DataGridViewImageColumn

        Public Sub New()

            Me.CellTemplate = New DataGridViewErrorIconCell()

            Me.ValueType = Me.CellTemplate.ValueType

        End Sub

    End Class

    Public Class DataGridViewErrorIconCell

        Inherits DataGridViewImageCell

        Public Sub New()

            Me.ValueType = GetType(Integer)

        End Sub

        Protected Overrides Function GetFormattedValue( _

            ByVal value As Object, ByVal rowIndex As Integer, _

            ByRef cellStyle As DataGridViewCellStyle, _

            ByVal valueTypeConverter As System.ComponentModel.TypeConverter, _

            ByVal formattedValueTypeConverter As System.ComponentModel.TypeConverter, _

            ByVal context As DataGridViewDataErrorContexts) As Object

            Select Case CInt(value)

                Case 1

                    Return SystemIcons.Information

                Case 2

                    Return SystemIcons.Warning

                Case 3

                    Return SystemIcons.Error

                Case Else

                    Return Nothing

            End Select

        End Function

        Public Overrides ReadOnly Property DefaultNewRowValue() As Object

            Get

                Return 0

            End Get

        End Property

    End Class

    用法如下

    Dim iconColumn As New DataGridViewErrorIconColumn()

    iconColumn.DataPropertyName = "Column1"

    DataGridView1.Columns.Add(iconColumn)

    57. DataGridView中显示进度条(ProgressBar)

    Imports System

    Imports System.Drawing

    Imports System.Windows.Forms

    Public Class DataGridViewProgressBarColumn

        Inherits DataGridViewTextBoxColumn

        Public Sub New()

            Me.CellTemplate = New DataGridViewProgressBarCell()

        End Sub

        Public Overrides Property CellTemplate() As DataGridViewCell

            Get

                Return MyBase.CellTemplate

            End Get

            Set(ByVal value As DataGridViewCell)

                If Not TypeOf value Is DataGridViewProgressBarCell Then

                    Throw New InvalidCastException( _

                        "DataGridViewProgressBarCellオブジェクトを" + _

                        "指定してください。")

                End If

                MyBase.CellTemplate = value

            End Set

        End Property

        Public Property Maximum() As Integer

            Get

                Return CType(Me.CellTemplate, DataGridViewProgressBarCell).Maximum

            End Get

            Set(ByVal value As Integer)

                If Me.Maximum = value Then

                    Return

                End If

                CType(Me.CellTemplate, DataGridViewProgressBarCell).Maximum = value

                If Me.DataGridView Is Nothing Then

                    Return

                End If

                Dim rowCount As Integer = Me.DataGridView.RowCount

                Dim i As Integer

                For i = 0 To rowCount - 1

                    Dim r As DataGridViewRow = Me.DataGridView.Rows.SharedRow(i)

                    CType(r.Cells(Me.Index), DataGridViewProgressBarCell).Maximum = _

                        value

                Next i

            End Set

        End Property

        Public Property Mimimum() As Integer

            Get

                Return CType(Me.CellTemplate, DataGridViewProgressBarCell).Mimimum

            End Get

            Set(ByVal value As Integer)

                If Me.Mimimum = value Then

                    Return

                End If

                CType(Me.CellTemplate, DataGridViewProgressBarCell).Mimimum = value

                If Me.DataGridView Is Nothing Then

                    Return

                End If

                Dim rowCount As Integer = Me.DataGridView.RowCount

                Dim i As Integer

                For i = 0 To rowCount - 1

                    Dim r As DataGridViewRow = Me.DataGridView.Rows.SharedRow(i)

                    CType(r.Cells(Me.Index), DataGridViewProgressBarCell).Mimimum = _

                        value

                Next i

            End Set

        End Property

    End Class

    Public Class DataGridViewProgressBarCell

        Inherits DataGridViewTextBoxCell

        Public Sub New()

            Me.maximumValue = 100

            Me.mimimumValue = 0

        End Sub

        Private maximumValue As Integer

        Public Property Maximum() As Integer

            Get

                Return Me.maximumValue

            End Get

            Set(ByVal value As Integer)

                Me.maximumValue = value

            End Set

        End Property

        Private mimimumValue As Integer

        Public Property Mimimum() As Integer

            Get

                Return Me.mimimumValue

            End Get

            Set(ByVal value As Integer)

                Me.mimimumValue = value

            End Set

        End Property

        Public Overrides ReadOnly Property ValueType() As Type

            Get

                Return GetType(Integer)

            End Get

        End Property

        Public Overrides ReadOnly Property DefaultNewRowValue() As Object

            Get

                Return 0

            End Get

        End Property

        Public Overrides Function Clone() As Object

            Dim cell As DataGridViewProgressBarCell = _

                CType(MyBase.Clone(), DataGridViewProgressBarCell)

            cell.Maximum = Me.Maximum

            cell.Mimimum = Me.Mimimum

            Return cell

        End Function

        Protected Overrides Sub Paint(ByVal graphics As Graphics, _

            ByVal clipBounds As Rectangle, _

            ByVal cellBounds As Rectangle, _

            ByVal rowIndex As Integer, _

            ByVal cellState As DataGridViewElementStates, _

            ByVal value As Object, _

            ByVal formattedValue As Object, _

            ByVal errorText As String, _

            ByVal cellStyle As DataGridViewCellStyle, _

            ByVal advancedBorderStyle As DataGridViewAdvancedBorderStyle, _

            ByVal paintParts As DataGridViewPaintParts)

            Dim intValue As Integer = 0

            If TypeOf value Is Integer Then

                intValue = CInt(value)

            End If

            If intValue < Me.mimimumValue Then

                intValue = Me.mimimumValue

            End If

            If intValue > Me.maximumValue Then

                intValue = Me.maximumValue

            End If

            Dim rate As Double = CDbl(intValue - Me.mimimumValue) / _

                (Me.maximumValue - Me.mimimumValue)

            If (paintParts And DataGridViewPaintParts.Border) = _

                    DataGridViewPaintParts.Border Then

                Me.PaintBorder(graphics, clipBounds, cellBounds, _

                    cellStyle, advancedBorderStyle)

            End If

            Dim borderRect As Rectangle = Me.BorderWidths(advancedBorderStyle)

            Dim paintRect As New Rectangle(cellBounds.Left + borderRect.Left, _

                cellBounds.Top + borderRect.Top, _

                cellBounds.Width - borderRect.Right, _

                cellBounds.Height - borderRect.Bottom)

            Dim isSelected As Boolean = _

                ((cellState And DataGridViewElementStates.Selected) = _

                    DataGridViewElementStates.Selected)

            Dim bkColor As Color

            If isSelected AndAlso _

                (paintParts And DataGridViewPaintParts.SelectionBackground) = _

                    DataGridViewPaintParts.SelectionBackground Then

                bkColor = cellStyle.SelectionBackColor

            Else

                bkColor = cellStyle.BackColor

            End If

            If (paintParts And DataGridViewPaintParts.Background) = _

                DataGridViewPaintParts.Background Then

                Dim backBrush As New SolidBrush(bkColor)

                Try

                    graphics.FillRectangle(backBrush, paintRect)

                Finally

                    backBrush.Dispose()

                End Try

            End If

            paintRect.Offset(cellStyle.Padding.Right, cellStyle.Padding.Top)

            paintRect.Width -= cellStyle.Padding.Horizontal

            paintRect.Height -= cellStyle.Padding.Vertical

            If (paintParts And DataGridViewPaintParts.ContentForeground) = _

                DataGridViewPaintParts.ContentForeground Then

                If ProgressBarRenderer.IsSupported Then

                    ProgressBarRenderer.DrawHorizontalBar(graphics, paintRect)

                    Dim barBounds As New Rectangle(paintRect.Left + 3, _

                        paintRect.Top + 3, _

                        paintRect.Width - 4, _

                        paintRect.Height - 6)

                    barBounds.Width = CInt(Math.Round((barBounds.Width * rate)))

                    ProgressBarRenderer.DrawHorizontalChunks(graphics, barBounds)

                Else

                    graphics.FillRectangle(Brushes.White, paintRect)

                    graphics.DrawRectangle(Pens.Black, paintRect)

                    Dim barBounds As New Rectangle(paintRect.Left + 1, _

                        paintRect.Top + 1, _

                        paintRect.Width - 1, _

                        paintRect.Height - 1)

                    barBounds.Width = CInt(Math.Round((barBounds.Width * rate)))

                    graphics.FillRectangle(Brushes.Blue, barBounds)

                End If

            End If

            If Me.DataGridView.CurrentCellAddress.X = Me.ColumnIndex AndAlso _

                Me.DataGridView.CurrentCellAddress.Y = Me.RowIndex AndAlso _

                (paintParts And DataGridViewPaintParts.Focus) = _

                    DataGridViewPaintParts.Focus AndAlso _

                Me.DataGridView.Focused Then

                Dim focusRect As Rectangle = paintRect

                focusRect.Inflate(-3, -3)

                ControlPaint.DrawFocusRectangle(graphics, focusRect)

            End If

            If (paintParts And DataGridViewPaintParts.ContentForeground) = _

                DataGridViewPaintParts.ContentForeground Then

                Dim txt As String = String.Format("{0}%", Math.Round((rate * 100)))

                Dim flags As TextFormatFlags = _

                    TextFormatFlags.HorizontalCenter Or _

                        TextFormatFlags.VerticalCenter

                Dim fColor As Color = cellStyle.ForeColor

                paintRect.Inflate(-2, -2)

                TextRenderer.DrawText(graphics, txt, cellStyle.Font, paintRect, fColor, flags)

            End If

            If (paintParts And DataGridViewPaintParts.ErrorIcon) = _

                    DataGridViewPaintParts.ErrorIcon AndAlso _

                Me.DataGridView.ShowCellErrors AndAlso _

                Not String.IsNullOrEmpty(errorText) Then

                Dim iconBounds As Rectangle = Me.GetErrorIconBounds(graphics, cellStyle, rowIndex)

                iconBounds.Offset(cellBounds.X, cellBounds.Y)

                Me.PaintErrorIcon(graphics, iconBounds, cellBounds, errorText)

            End If

        End Sub

    End Class

    用法如下

    Dim pbColumn As New DataGridViewProgressBarColumn()

    pbColumn.DataPropertyName = "Column1"

    DataGridView1.Columns.Add(pbColumn)

    58. DataGridView中添加MaskedTextBox

    Imports System

    Imports System.Windows.Forms

    Public Class DataGridViewMaskedTextBoxColumn

        Inherits DataGridViewColumn

        Public Sub New()

            MyBase.New(New DataGridViewMaskedTextBoxCell())

        End Sub

        Private maskValue As String = ""

        Public Property Mask() As String

            Get

                Return Me.maskValue

            End Get

            Set(ByVal value As String)

                Me.maskValue = value

            End Set

        End Property

        Public Overrides Function Clone() As Object

            Dim col As DataGridViewMaskedTextBoxColumn = _

                CType(MyBase.Clone(), DataGridViewMaskedTextBoxColumn)

            col.Mask = Me.Mask

            Return col

        End Function

        Public Overrides Property CellTemplate() As DataGridViewCell

            Get

                Return MyBase.CellTemplate

            End Get

            Set(ByVal value As DataGridViewCell)

                If Not TypeOf value Is DataGridViewMaskedTextBoxCell Then

                    Throw New InvalidCastException( _

                        "DataGridViewMaskedTextBoxCellオブジェクトを" + _

                        "指定してください。")

                End If

                MyBase.CellTemplate = value

            End Set

        End Property

    End Class

    Public Class DataGridViewMaskedTextBoxCell

        Inherits DataGridViewTextBoxCell

        Public Sub New()

        End Sub

        Public Overrides Sub InitializeEditingControl(ByVal rowIndex As Integer, _

            ByVal initialFormattedValue As Object, _

            ByVal dataGridViewCellStyle As DataGridViewCellStyle)

            MyBase.InitializeEditingControl(rowIndex, initialFormattedValue, dataGridViewCellStyle)

            Dim maskedBox As DataGridViewMaskedTextBoxEditingControl = _

                Me.DataGridView.EditingControl

            If Not (maskedBox Is Nothing) Then

                maskedBox.Text = IIf(Me.Value Is Nothing, "", Me.Value.ToString())

                Dim column As DataGridViewMaskedTextBoxColumn = Me.OwningColumn

                If Not (column Is Nothing) Then

                    maskedBox.Mask = column.Mask

                End If

            End If

        End Sub

        Public Overrides ReadOnly Property EditType() As Type

            Get

                Return GetType(DataGridViewMaskedTextBoxEditingControl)

            End Get

        End Property

        Public Overrides ReadOnly Property ValueType() As Type

            Get

                Return GetType(Object)

            End Get

        End Property

        Public Overrides ReadOnly Property DefaultNewRowValue() As Object

            Get

                Return MyBase.DefaultNewRowValue

            End Get

        End Property

    End Class

    Public Class DataGridViewMaskedTextBoxEditingControl

        Inherits MaskedTextBox

        Implements IDataGridViewEditingControl

        Private dataGridView As DataGridView

        Private rowIndex As Integer

        Private valueChanged As Boolean

        Public Sub New()

            Me.TabStop = False

        End Sub

        Public Function GetEditingControlFormattedValue( _

            ByVal context As DataGridViewDataErrorContexts) As Object _

            Implements IDataGridViewEditingControl.GetEditingControlFormattedValue

            Return Me.Text

        End Function

        Public Property EditingControlFormattedValue() As Object _

            Implements IDataGridViewEditingControl.EditingControlFormattedValue

            Get

                Return Me.GetEditingControlFormattedValue(DataGridViewDataErrorContexts.Formatting)

            End Get

            Set(ByVal value As Object)

                Me.Text = CStr(value)

            End Set

        End Property

        Public Sub ApplyCellStyleToEditingControl( _

            ByVal dataGridViewCellStyle As DataGridViewCellStyle) _

            Implements IDataGridViewEditingControl.ApplyCellStyleToEditingControl

            Me.Font = dataGridViewCellStyle.Font

            Me.ForeColor = dataGridViewCellStyle.ForeColor

            Me.BackColor = dataGridViewCellStyle.BackColor

            Select Case dataGridViewCellStyle.Alignment

                Case DataGridViewContentAlignment.BottomCenter, _

                        DataGridViewContentAlignment.MiddleCenter, _

                        DataGridViewContentAlignment.TopCenter

                    Me.TextAlign = HorizontalAlignment.Center

                Case DataGridViewContentAlignment.BottomRight, _

                        DataGridViewContentAlignment.MiddleRight, _

                        DataGridViewContentAlignment.TopRight

                    Me.TextAlign = HorizontalAlignment.Right

                Case Else

                    Me.TextAlign = HorizontalAlignment.Left

            End Select

        End Sub

        Public Property EditingControlDataGridView() As DataGridView _

            Implements IDataGridViewEditingControl.EditingControlDataGridView

            Get

                Return Me.dataGridView

            End Get

            Set(ByVal value As DataGridView)

                Me.dataGridView = value

            End Set

        End Property

        Public Property EditingControlRowIndex() As Integer _

            Implements IDataGridViewEditingControl.EditingControlRowIndex

            Get

                Return Me.rowIndex

            End Get

            Set(ByVal value As Integer)

                Me.rowIndex = value

            End Set

        End Property

        Public Property EditingControlValueChanged() As Boolean _

            Implements IDataGridViewEditingControl.EditingControlValueChanged

            Get

                Return Me.valueChanged

            End Get

            Set(ByVal value As Boolean)

                Me.valueChanged = value

            End Set

        End Property

        Public Function EditingControlWantsInputKey(ByVal keyData As Keys, _

            ByVal dataGridViewWantsInputKey As Boolean) As Boolean _

            Implements IDataGridViewEditingControl.EditingControlWantsInputKey

            Select Case keyData And Keys.KeyCode

                Case Keys.Right, Keys.End, Keys.Left, Keys.Home

                    Return True

                Case Else

                    Return False

            End Select

        End Function

        Public ReadOnly Property EditingPanelCursor() As Cursor _

            Implements IDataGridViewEditingControl.EditingPanelCursor

            Get

                Return MyBase.Cursor

            End Get

        End Property

        Public Sub PrepareEditingControlForEdit(ByVal selectAll As Boolean) _

            Implements IDataGridViewEditingControl.PrepareEditingControlForEdit

            If selectAll Then

                Me.SelectAll()

            Else

                Me.SelectionStart = Me.TextLength

            End If

        End Sub

        Public ReadOnly Property RepositionEditingControlOnValueChange() _

            As Boolean _

            Implements _

                IDataGridViewEditingControl.RepositionEditingControlOnValueChange

            Get

                Return False

            End Get

        End Property

        Protected Overrides Sub OnTextChanged(ByVal e As EventArgs)

            MyBase.OnTextChanged(e)

            Me.valueChanged = True

            Me.dataGridView.NotifyCurrentCellDirty(True)

        End Sub

    End Class

    用法如下

    'DataGridViewMaskedTextBoxColumnを作成

    Dim maskedColumn As New DataGridViewMaskedTextBoxColumn()

    maskedColumn.DataPropertyName = "Column1"

    maskedColumn.Mask = "000"

    DataGridView1.Columns.Add(maskedColumn)

    59. DataGridView中Enter键按下焦点移至旁边的单元格

    Imports System

    Imports System.Windows.Forms

    Public Class DataGridViewEx

        Inherits DataGridView

        Protected Overrides Function ProcessDialogKey( _

                ByVal keyData As Keys) As Boolean

            If (keyData And Keys.KeyCode) = Keys.Enter Then

                Return Me.ProcessTabKey(keyData)

            End If

            Return MyBase.ProcessDialogKey(keyData)

        End Function

        Protected Overrides Function ProcessDataGridViewKey( _

                ByVal e As KeyEventArgs) As Boolean

            If e.KeyCode = Keys.Enter Then

                Return Me.ProcessTabKey(e.KeyCode)

            End If

            Return MyBase.ProcessDataGridViewKey(e)

        End Function

    End Class

    60. DataGridView行集合化(Group)

    Private defaultCellStyle As DataGridViewCellStyle

    Private groupCellStyle As DataGridViewCellStyle

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

        Me.defaultCellStyle = New DataGridViewCellStyle()

        Me.groupCellStyle = New DataGridViewCellStyle()

        Me.groupCellStyle.ForeColor = Color.White

        Me.groupCellStyle.BackColor = Color.DarkGreen

        Me.groupCellStyle.SelectionBackColor = Color.DarkBlue

    End Sub

    Private Sub DataGridView1_CellFormatting(ByVal sender As Object, _

            ByVal e As DataGridViewCellFormattingEventArgs) _

            Handles DataGridView1.CellFormatting

        Dim dgv As DataGridView = CType(sender, DataGridView)

        If e.ColumnIndex = 0 AndAlso e.RowIndex >= 0 AndAlso _

            e.RowIndex <> dgv.NewRowIndex Then

            If e.RowIndex = 0 OrElse _

                Not dgv(e.ColumnIndex, e.RowIndex - 1).Value.Equals(e.Value) Then

                dgv.Rows(e.RowIndex).DefaultCellStyle = Me.groupCellStyle

            Else

                dgv.Rows(e.RowIndex).DefaultCellStyle = Me.defaultCellStyle

                e.Value = ""

                e.FormattingApplied = True

            End If

        End If

    End Sub

  • 相关阅读:
    类中以双下划线開始的方法
    Dynamics CRM2016 新功能之从CRM APP中导出数据至EXCEL
    敏捷项目管理实践
    Hibernate环境搭建
    ubuntu12.04更新软件源时出现校验和不符
    修炼你自己
    http自己定义超时检測方法、主动抛出异常
    sql server 2008安装图解
    Ural 1353 Milliard Vasya&#39;s Function(DP)
    待字闺中之构造最大数分析
  • 原文地址:https://www.cnblogs.com/zhouto/p/1885553.html
Copyright © 2020-2023  润新知