DataGridView用法合集【精品】

目录

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

2.DataGridView编辑属性

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

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

[5. DataGridView删除行可否设定](#5. DataGridView删除行可否设定)

[6. DataGridView行列不表示和删除](#6. DataGridView行列不表示和删除)

[7. DataGridView行列宽度高度设置为不能编辑](#7. DataGridView行列宽度高度设置为不能编辑)

[8. DataGridView行高列幅自动调整](#8. DataGridView行高列幅自动调整)

[9. DataGridView指定行列冻结](#9. DataGridView指定行列冻结)

[10. DataGridView列顺序变更可否设定](#10. DataGridView列顺序变更可否设定)

[11. DataGridView行复数选择](#11. DataGridView行复数选择)

[12. DataGridView选择的行、列、单元格取得](#12. DataGridView选择的行、列、单元格取得)

[13. DataGridView指定单元格是否表示](#13. DataGridView指定单元格是否表示)

[14. DataGridView表头部单元格取得](#14. DataGridView表头部单元格取得)

[15. DataGridView表头部单元格文字列设定](#15. DataGridView表头部单元格文字列设定)

[16. DataGridView选择的部分拷贝至剪贴板](#16. DataGridView选择的部分拷贝至剪贴板)

17.DataGridView粘贴

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

19.DataGridView中的ContextMenuStrip属性

[20. DataGridView指定滚动框位置](#20. DataGridView指定滚动框位置)

[21. DataGridView手动追加列](#21. DataGridView手动追加列)

[22. DataGridView全体分界线样式设置](#22. DataGridView全体分界线样式设置)

[23. DataGridView根据单元格属性更改显示内容](#23. DataGridView根据单元格属性更改显示内容)

[24. DataGridView新追加行的行高样式设置](#24. DataGridView新追加行的行高样式设置)

[25. DataGridView新追加行单元格默认值设置](#25. DataGridView新追加行单元格默认值设置)

[26. DataGridView单元格数据错误标签表示](#26. DataGridView单元格数据错误标签表示)

[27. DataGridView单元格内输入值正确性判断](#27. DataGridView单元格内输入值正确性判断)

[28. DataGridView单元格输入错误值事件的捕获](#28. DataGridView单元格输入错误值事件的捕获)

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

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

[31. DataGridView自动行排序禁止情况下的排序](#31. DataGridView自动行排序禁止情况下的排序)

[32. DataGridView指定列指定排序](#32. DataGridView指定列指定排序)

[33. DataGridView单元格样式设置](#33. DataGridView单元格样式设置)

[34. DataGridView文字表示位置的设定](#34. DataGridView文字表示位置的设定)

[35. DataGridView单元格内文字列换行](#35. DataGridView单元格内文字列换行)

[36. DataGridView单元格DBNull值表示的设定](#36. DataGridView单元格DBNull值表示的设定)

[37. DataGridView单元格样式格式化](#37. DataGridView单元格样式格式化)

[38. DataGridView指定单元格颜色设定](#38. DataGridView指定单元格颜色设定)

[39. DataGridView单元格文字字体设置](#39. DataGridView单元格文字字体设置)

[40. DataGridView根据单元格值设定单元格样式](#40. DataGridView根据单元格值设定单元格样式)

[41. DataGridView设置单元格背景颜色](#41. DataGridView设置单元格背景颜色)

[42. DataGridView行样式描画](#42. DataGridView行样式描画)

[43. DataGridView显示行号](#43. DataGridView显示行号)

[44. DataGridView焦点所在单元格焦点框不显示的设定](#44. DataGridView焦点所在单元格焦点框不显示的设定)

[45. DataGridView列中显示选择框CheckBox](#45. DataGridView列中显示选择框CheckBox)

[46. DataGridView中显示下拉框ComboBox](#46. DataGridView中显示下拉框ComboBox)

[47. DataGridView单击打开下拉框](#47. DataGridView单击打开下拉框)

[48. DataGridView中显示按钮](#48. DataGridView中显示按钮)

[49. DataGridView中显示链接](#49. DataGridView中显示链接)

[50. DataGridView中显示图像](#50. DataGridView中显示图像)

[51. DataGridView编辑中单元格控件取得](#51. DataGridView编辑中单元格控件取得)

[52. DataGridView输入自动完成](#52. DataGridView输入自动完成)

[53. DataGridView单元格编辑时键盘KEY事件取得](#53. DataGridView单元格编辑时键盘KEY事件取得)

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

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

[56. DataGridView根据值不同在另一列中显示相应图片](#56. DataGridView根据值不同在另一列中显示相应图片)

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

[58. DataGridView中添加MaskedTextBox](#58. DataGridView中添加MaskedTextBox)


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

[VB.NET]

Console.WriteLine(DataGridView1.CurrentCell.Value)

Console.WriteLine(DataGridView1.CurrentCell.ColumnIndex)

Console.WriteLine(DataGridView1.CurrentCell.RowIndex)

DataGridView1.CurrentCell = DataGridView1(0, 0)

[C#]

Console.WriteLine(DataGridView1.CurrentCell.Value);

Console.WriteLine(DataGridView1.CurrentCell.ColumnIndex);

Console.WriteLine(DataGridView1.CurrentCell.RowIndex);

DataGridView1.CurrentCell = DataGridView1[0, 0];

2.DataGridView编辑属性

全部单元格编辑属性

[VB.NET]

DataGridView1.ReadOnly = True

[C#]

DataGridView1.ReadOnly = true;

指定行列单元格编辑属性

[VB.NET]

DataGridView1.Columns(1).ReadOnly = True

DataGridView1.Rows(2).ReadOnly = True

DataGridView1(0, 0).ReadOnly = True

[C#]

DataGridView1.Columns[1].ReadOnly = true;

DataGridView1.Rows[2].ReadOnly = true;

DataGridView1[0, 0].ReadOnly = true;

根据条件判断单元格的编辑属性

下例中column2的值是True的时候,Column1设为可编辑

[VB.NET]

vbnet 复制代码
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

[C#]

cs 复制代码
private void DataGridView1_CellBeginEdit(object sender,
    DataGridViewCellCancelEventArgs e)
{
    DataGridView dgv = (DataGridView)sender;
    if (dgv.Columns[e.ColumnIndex].Name == "Column1" &&
        !(bool)dgv["Column2", e.RowIndex].Value)
    {
        e.Cancel = true;
    }
}

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

[VB.NET]

DataGridView1.AllowUserToAddRows = False

[C#]

DataGridView1.AllowUserToAddRows = false;

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

[VB.NET]

vbnet 复制代码
If DataGridView1.CurrentRow.IsNewRow Then
    Console.WriteLine("现在的单元格所在的行是新的行")
Else
    Console.WriteLine("当前单元格所在的行不是新的行。")
End If

[C#]

cs 复制代码
if (DataGridView1.CurrentRow.IsNewRow)
    Console.WriteLine("现在的单元格所在的行是新的行");
else
    Console.WriteLine("当前单元格所在的行不是新的行");

5. DataGridView删除行可否设定

[VB.NET]

DataGridView1.AllowUserToDeleteRows = False

[C#]

DataGridView1.AllowUserToDeleteRows = false;

根据条件判断当前行是否要删除

[VB.NET]

vbnet 复制代码
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

[C#]

cs 复制代码
private void DataGridView1_UserDeletingRow(
    object sender, DataGridViewRowCancelEventArgs e)
{
    if (MessageBox.Show("要删除这一列吗?", "删除确认",MessageBoxButtons.OKCancel,MessageBoxIcon.Question) != DialogResult.OK)
    {
        e.Cancel = true;
    }
}

6. DataGridView行列不表示和删除

行列不表示

[VB.NET]

DataGridView1.Columns(0).Visible = False

DataGridView1.Rows(0).Visible = False

[C#]

DataGridView1.Columns[0].Visible = false;

DataGridView1.Rows[0].Visible = false;

行列表头部分不表示

[VB.NET]

DataGridView1.ColumnHeadersVisible = False

DataGridView1.RowHeadersVisible = False

[C#]

DataGridView1.ColumnHeadersVisible = false;

DataGridView1.RowHeadersVisible = false;

指定行列删除

[VB.NET]

DataGridView1.Columns.Remove("Column1")

DataGridView1.Columns.RemoveAt(0)

DataGridView1.Rows.RemoveAt(0)

[C#]

DataGridView1.Columns.Remove("Column1");

DataGridView1.Columns.RemoveAt(0);

DataGridView1.Rows.RemoveAt(0);

选择的行列删除(多行列)

[VB.NET]

vbnet 复制代码
Dim r As DataGridViewRow
For Each r In DataGridView1.SelectedRows
    If Not r.IsNewRow Then
        DataGridView1.Rows.Remove(r)
    End If
Next r

[C#]

cs 复制代码
foreach (DataGridViewRow r in DataGridView1.SelectedRows)
{
    if (!r.IsNewRow)
    {
        DataGridView1.Rows.Remove(r);
    }
}

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

[VB.NET]

DataGridView1.AllowUserToResizeColumns = False

DataGridView1.AllowUserToResizeRows = False

[C#]

DataGridView1.AllowUserToResizeColumns = false;

DataGridView1.AllowUserToResizeRows = false;

指定行列宽度高度设置为不能编辑

[VB.NET]

DataGridView1.Columns(0).Resizable = DataGridViewTriState.False

DataGridView1.Rows(0).Resizable = DataGridViewTriState.False

[C#]

DataGridView1.Columns[0].Resizable = DataGridViewTriState.False;

DataGridView1.Rows[0].Resizable = DataGridViewTriState.False;

列幅行高最小值设定

[VB.NET]

DataGridView1.Columns(0).MinimumWidth = 100

DataGridView1.Rows(0).MinimumHeight = 50

[C#]

DataGridView1.Columns[0].MinimumWidth = 100;

DataGridView1.Rows[0].MinimumHeight = 50;

行列表头部分行高列幅设置为不能编辑

[VB.NET]

vbnet 复制代码
DataGridView1.ColumnHeadersHeightSizeMode =DataGridViewColumnHeadersHeightSizeMode.DisableResizing
DataGridView1.RowHeadersWidthSizeMode = DataGridViewRowHeadersWidthSizeMode.EnableResizing

[C#]

cs 复制代码
DataGridView1.ColumnHeadersHeightSizeMode=DataGridViewColumnHeadersHeightSizeMode.DisableResizing;
DataGridView1.RowHeadersWidthSizeMode=DataGridViewRowHeadersWidthSizeMode.EnableResizing;

8. DataGridView行高列幅自动调整

[VB.NET]

DataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells

DataGridView1.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells

[C#]

DataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;

DataGridView1.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells;

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

[VB.NET]

DataGridView1.ColumnHeadersHeightSizeMode = _

DataGridViewColumnHeadersHeightSizeMode.AutoSize

DataGridView1.RowHeadersWidthSizeMode = _

DataGridViewRowHeadersWidthSizeMode.AutoSizeToAllHeaders

[C#]

DataGridView1.ColumnHeadersHeightSizeMode =

DataGridViewColumnHeadersHeightSizeMode.AutoSize;

DataGridView1.RowHeadersWidthSizeMode =

DataGridViewRowHeadersWidthSizeMode.AutoSizeToAllHeaders;

指定列自动调整

[VB.NET]

DataGridView1.Columns(0).AutoSizeMode = _

DataGridViewAutoSizeColumnMode.DisplayedCells

[C#]

DataGridView1.Columns[0].AutoSizeMode =

DataGridViewAutoSizeColumnMode.DisplayedCells;

9. DataGridView指定行列冻结

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

[VB.NET]

DataGridView1.Columns(1).Frozen = True

[C#]

DataGridView1.Columns[1].Frozen = true;

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

[VB.NET]

DataGridView1.Rows(2).Frozen = True

[C#]

DataGridView1.Rows[2].Frozen = true;

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

[VB.NET]

DataGridView1(0, 0). Frozen = True

[C#]

DataGridView1[0, 0]. Frozen = true;

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

[VB.NET]

DataGridView1.AllowUserToOrderColumns = True

[C#]

DataGridView1.AllowUserToOrderColumns = true;

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

变更后列位置取得

[VB.NET]

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

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

[C#]

Console.WriteLine(DataGridView1.Columns["Column1"].DisplayIndex);

DataGridView1.Columns["Column1"].DisplayIndex = 0;

11. DataGridView行复数选择

复数行选择不可

[VB.NET]

DataGridView1.MultiSelect = False

[C#]

DataGridView1.MultiSelect = false;

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

[VB.NET]

DataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect

[C#]

DataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;

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

[VB.NET]

vbnet 复制代码
For Each c As DataGridViewCell In DataGridView1.SelectedCells
    Console.WriteLine("{0}, {1}", c.ColumnIndex, c.RowIndex)
Next c
For Each r As DataGridViewRow In DataGridView1.SelectedRows
    Console.WriteLine(r.Index)
Next r
For Each c As DataGridViewColumn In DataGridView1.SelectedColumns
    Console.WriteLine(c.Index)
Next c

[C#]

cs 复制代码
foreach (DataGridViewCell c in DataGridView1.SelectedCells)
{
    Console.WriteLine("{0}, {1}", c.ColumnIndex, c.RowIndex);
}
foreach (DataGridViewRow r in DataGridView1.SelectedRows)
{
    Console.WriteLine(r.Index);
}
foreach (DataGridViewColumn c in DataGridView1.SelectedColumns)
{
    Console.WriteLine(c.Index);
}

指定行、列、单元格取得

[VB.NET]

DataGridView1(0, 0).Selected = True

DataGridView1.Rows(1).Selected = True

DataGridView1.Columns(2).Selected = True

[C#]

DataGridView1[0, 0].Selected = true;

DataGridView1.Rows[1].Selected = true;

DataGridView1.Columns[2].Selected = true;

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

[VB.NET]

If Not DataGridView1(0, 0).Displayed AndAlso DataGridView1(0, 0).Visible Then

DataGridView1.CurrentCell = DataGridView1(0, 0)

End If

[C#]

if (!DataGridView1[0, 0].Displayed && DataGridView1[0, 0].Visible)

{

DataGridView1.CurrentCell = DataGridView1[0, 0];

}

14. DataGridView表头部单元格取得

[VB.NET]

DataGridView1.Columns(0).HeaderCell.Value = "开头列"

DataGridView1.Rows(0).HeaderCell.Value = "开头行"

DataGridView1.TopLeftHeaderCell.Value = "左上"

[C#]

DataGridView1.Columns[0].HeaderCell.Value = "开头列";

DataGridView1.Rows[0].HeaderCell.Value = "开头行";

DataGridView1.TopLeftHeaderCell.Value = "左上";

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

更改列Header表示文字列

[VB.NET]

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

[C#]

DataGridView1.Columns[0].HeaderText = "はじめの列";

更改行Header表示文字列

[VB.NET]

vbnet 复制代码
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)

[C#]

cs 复制代码
for (int i = 0; i < DataGridView1.Rows.Count; i++)
{
    DataGridView1.Rows[i].HeaderCell.Value = i.ToString();
}
DataGridView1.AutoResizeRowHeadersWidth(DataGridViewRowHeadersWidthSizeMode.AutoSizeToAllHeaders);

最左上Header单元格文字列

[VB.NET]

DataGridView1.TopLeftHeaderCell.Value = "/"

[C#]

DataGridView1.TopLeftHeaderCell.Value = "/";

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

拷贝模式设定

[VB.NET]

DataGridView1.ClipboardCopyMode = DataGridViewClipboardCopyMode.EnableWithoutHeaderText

[C#]

DataGridView1.ClipboardCopyMode =DataGridViewClipboardCopyMode.EnableWithoutHeaderText;

选中部分拷贝

[VB.NET]

Clipboard.SetDataObject(DataGridView1.GetClipboardContent())

[C#]

Clipboard.SetDataObject(DataGridView1.GetClipboardContent());

17.DataGridView粘贴

[VB.NET]

vbnet 复制代码
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

[C#]

cs 复制代码
if (DataGridView1.CurrentCell == null)
    return;
int insertRowIndex = DataGridView1.CurrentCell.RowIndex;
string pasteText = Clipboard.GetText();
if (string.IsNullOrEmpty(pasteText))
    return;
pasteText = pasteText.Replace("/r/n", "/n");
pasteText = pasteText.Replace('/r', '/n');
pasteText.TrimEnd(new char[] { '/n' });
string[] lines = pasteText.Split('/n');
bool isHeader = true;
foreach (string line in lines)
{
    if (isHeader)
    {
        isHeader = false;
        continue;
    }
    string[] vals = line.Split('/t');
    if (vals.Length - 1 != DataGridView1.ColumnCount)
        throw new ApplicationException("列数が違います。");
    DataGridViewRow row = DataGridView1.Rows[insertRowIndex];
    row.HeaderCell.Value = vals[0];
    for (int i = 0; i < row.Cells.Count; i++)
    {
        row.Cells[i].Value = vals[i + 1];
    }
    insertRowIndex++;
}

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

[VB.NET]

DataGridView1(0, 0).ToolTipText = "这个单元格是不可更改的"

DataGridView1.Columns(0).ToolTipText = "你可以在这一列输入数字"

DataGridView1.Rows(0).HeaderCell.ToolTipText = "这行的单元格是不可更改的"

[C#]

DataGridView1[0, 0].ToolTipText = "这个单元格是不可更改的";

DataGridView1.Columns[0].ToolTipText = "你可以在这一列输入数字";

DataGridView1.Rows[0].HeaderCell.ToolTipText = "这行的单元格是不可更改的";

CellToolTipTextNeeded事件,在多个单元格使用相同的ToolTips的时候,可以用该事件,下例为显示当前单元格的行号和列号

[VB.NET]

vbnet 复制代码
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

[C#]

cs 复制代码
private void DataGridView1_CellToolTipTextNeeded(object sender,
    DataGridViewCellToolTipTextNeededEventArgs e)
{
e.ToolTipText = e.ColumnIndex.ToString() + ", " + e.RowIndex.ToString();
}

19.DataGridView中的ContextMenuStrip属性

[VB.NET]

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

[C#]

DataGridView1.ContextMenuStrip = this.ContextMenuStrip1;

DataGridView1.Columns[0].ContextMenuStrip = this.ContextMenuStrip2;

DataGridView1.Columns[0].HeaderCell.ContextMenuStrip = this.ContextMenuStrip2;

DataGridView1.Rows[0].ContextMenuStrip = this.ContextMenuStrip3;

DataGridView1[0, 1].ContextMenuStrip = this.ContextMenuStrip4;

也可以用CellContextMenuStripNeeded、RowContextMenuStripNeeded属性进行定义

[VB.NET]

vbnet 复制代码
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

[C#]

cs 复制代码
private void DataGridView1_CellContextMenuStripNeeded(object sender,
    DataGridViewCellContextMenuStripNeededEventArgs e)
{
    DataGridView dgv = (DataGridView)sender;
    if (e.RowIndex < 0)
    {
        e.ContextMenuStrip = this.ContextMenuStrip1;
    }
    else if (e.ColumnIndex < 0)
    {
        e.ContextMenuStrip = this.ContextMenuStrip2;
    }
    else if (dgv[e.ColumnIndex, e.RowIndex].Value is int)
    {
        e.ContextMenuStrip = this.ContextMenuStrip3;
    }
}

20. DataGridView指定滚动框位置

[VB.NET]

DataGridView1.FirstDisplayedScrollingRowIndex = 0

DataGridView1.FirstDisplayedScrollingColumnIndex = 0

[C#]

DataGridView1.FirstDisplayedScrollingRowIndex = 0;

DataGridView1.FirstDisplayedScrollingColumnIndex = 0;

21. DataGridView手动追加列

[VB.NET]

DataGridView1.AutoGenerateColumns = False

DataGridView1.DataSource = BindingSource1

Dim textColumn As New DataGridViewTextBoxColumn()

textColumn.DataPropertyName = "Column1"

textColumn.Name = "Column1"

textColumn.HeaderText = "Column1"

DataGridView1.Columns.Add(textColumn)

[C#]

DataGridView1.AutoGenerateColumns = false;

DataGridView1.DataSource = BindingSource1;

DataGridViewTextBoxColumn textColumn = new DataGridViewTextBoxColumn();

textColumn.DataPropertyName = "Column1";

textColumn.Name = "Column1";

textColumn.HeaderText = "Column1";

DataGridView1.Columns.Add(textColumn);

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

[VB.NET]

DataGridView1.BorderStyle = BorderStyle.Fixed3D

[C#]

DataGridView1.BorderStyle = BorderStyle.Fixed3D;

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

[VB.NET]

DataGridView1.AdvancedCellBorderStyle.Top = DataGridViewAdvancedCellBorderStyle.InsetDouble

DataGridView1.AdvancedCellBorderStyle.Right = DataGridViewAdvancedCellBorderStyle.Inset

DataGridView1.AdvancedCellBorderStyle.Bottom = DataGridViewAdvancedCellBorderStyle.Inset

DataGridView1.AdvancedCellBorderStyle.Left = DataGridViewAdvancedCellBorderStyle.InsetDouble

[C#]

DataGridView1.AdvancedCellBorderStyle.Top = DataGridViewAdvancedCellBorderStyle.InsetDouble;

DataGridView1.AdvancedCellBorderStyle.Right = DataGridViewAdvancedCellBorderStyle.Inset;

DataGridView1.AdvancedCellBorderStyle.Bottom = DataGridViewAdvancedCellBorderStyle.Inset;

DataGridView1.AdvancedCellBorderStyle.Left = DataGridViewAdvancedCellBorderStyle.InsetDouble;

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

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

[VB.NET]

vbnet 复制代码
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

[C#]

vbnet 复制代码
private void DataGridView1_CellFormatting(object sender,
    DataGridViewCellFormattingEventArgs e)
{
    DataGridView dgv = (DataGridView)sender;
    if (dgv.Columns[e.ColumnIndex].Name == "Column1" && e.Value is string)
    {
        string str = e.Value.ToString();
        e.Value = str.ToUpper();
        e.FormattingApplied = true;
    }
}

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

行高设置

[VB.NET]

DataGridView1.RowTemplate.Height = 50

DataGridView1.RowTemplate.MinimumHeight = 50

[C#]

DataGridView1.RowTemplate.Height = 50;

DataGridView1.RowTemplate.MinimumHeight = 50;

样式设置

[VB.NET]

DataGridView1.DefaultCellStyle.BackColor = Color.Yellow

[C#]

DataGridView1.DefaultCellStyle.BackColor = Color.Yellow;

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

[VB.NET]

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

[C#]

private void DataGridView1_DefaultValuesNeeded(object sender,

DataGridViewRowEventArgs e)

{

e.Row.Cells["Column1"].Value = 0;

e.Row.Cells["Column2"].Value = "-";

}

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

[VB.NET]

DataGridView1(0, 0).ErrorText = "请确认单元格的值。"

DataGridView1.Rows(3).ErrorText = "不能输入负值。"

[C#]

DataGridView1[0, 0].ErrorText = "请确认单元格的值。";

DataGridView1.Rows[3].ErrorText = "不能输入负值。";

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

[VB.NET]

vbnet 复制代码
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

[C#]

cs 复制代码
private void DataGridView1_CellErrorTextNeeded(object sender,
    DataGridViewCellErrorTextNeededEventArgs e)
{
    DataGridView dgv = (DataGridView)sender;
    object cellVal = dgv[e.ColumnIndex, e.RowIndex].Value;
    if (cellVal is int && ((int)cellVal) < 0)
    {
        e.ErrorText = "不能输入负整数。";
    }
}
private void DataGridView1_RowErrorTextNeeded(object sender,
    DataGridViewRowErrorTextNeededEventArgs e)
{
    DataGridView dgv = (DataGridView)sender;
    if (dgv["Column1", e.RowIndex].Value == DBNull.Value &&
        dgv["Column2", e.RowIndex].Value == DBNull.Value)
    {
        e.ErrorText =
            "请至少在Column1和Column2中输入值。";
    }
}

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

[VB.NET]

vbnet 复制代码
'CellValidating活动处理程序
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 = "没有输入值。"
        '为了取消输入的值并复原,如下所示
        'dgv.CancelEdit()
        '取消
        e.Cancel = True
    End If
End Sub
'CellValidated事件处理程序
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

[C#]

cs 复制代码
//CellValidating活动处理程序
private void DataGridView1_CellValidating(object sender,
    DataGridViewCellValidatingEventArgs e)
{
    DataGridView dgv = (DataGridView)sender;
    if (dgv.Columns[e.ColumnIndex].Name == "Column1" &&
        e.FormattedValue.ToString() == "")
    {
        //在行中设置错误文本
        dgv.Rows[e.RowIndex].ErrorText = "没有输入值。";
        //为了取消输入的值并复原,如下所示。
        //dgv.CancelEdit();
        //取消
        e.Cancel = true;
    }
}
//CellValidated事件处理程序
private void DataGridView1_CellValidated(object sender,
    DataGridViewCellEventArgs e)
{
    DataGridView dgv = (DataGridView)sender;
    //消除错误文本
    dgv.Rows[e.RowIndex].ErrorText = null;
}

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

[VB.NET]

vbnet 复制代码
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

[C#]

cs 复制代码
private void DataGridView1_DataError(object sender,

    DataGridViewDataErrorEventArgs e)

{

    if (e.Exception != null)

    {

        MessageBox.Show(this,

            string.Format("({0}, {1}) 的单元格发生了错误。/n/n说明: {2}",

            e.ColumnIndex, e.RowIndex, e.Exception.Message),

            "发生了错误",

            MessageBoxButtons.OK, MessageBoxIcon.Error);

    }

}

输入错误值时返回原先数据

[VB.NET]

vbnet 复制代码
Private Sub DataGridView1_DataError(ByVal sender As Object, _
        ByVal e As DataGridViewDataErrorEventArgs) _
        Handles DataGridView1.DataError
    e.Cancel = False
End Sub

[C#]

vbnet 复制代码
private void DataGridView1_DataError(object sender,
    DataGridViewDataErrorEventArgs e)
{

    e.Cancel = false;
}

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

[VB.NET]

For Each c As DataGridViewColumn In DataGridView1.Columns

c.SortMode = DataGridViewColumnSortMode.NotSortable

Next c

[C#]

foreach (DataGridViewColumn c in DataGridView1.Columns)

c.SortMode = DataGridViewColumnSortMode.NotSortable;

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

[VB.NET]

vbnet 复制代码
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

[C#]

cs 复制代码
private void Form1_Load(object sender, EventArgs e)
{
    foreach (DataGridViewColumn c in DataGridView1.Columns)
        c.SortMode = DataGridViewColumnSortMode.Automatic;
}
private void Button1_Click(object sender, EventArgs e)
{
    if (DataGridView1.CurrentCell == null)
        return;
    DataGridViewColumn sortColumn = DataGridView1.CurrentCell.OwningColumn;
    ListSortDirection sortDirection = ListSortDirection.Ascending;
    if (DataGridView1.SortedColumn != null &&
        DataGridView1.SortedColumn.Equals(sortColumn))
    {
        sortDirection =
            DataGridView1.SortOrder == SortOrder.Ascending ?
            ListSortDirection.Descending : ListSortDirection.Ascending;
    }
    DataGridView1.Sort(sortColumn, sortDirection);
}

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

[VB.NET]

vbnet 复制代码
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

[C#]

cs 复制代码
private void Form1_Load(object sender, EventArgs e)
{
    DataGridView1.RowsAdded += new DataGridViewRowsAddedEventHandler(
        DataGridView1_RowsAdded);
    DataGridView1.CellValueChanged += new DataGridViewCellEventHandler(
        DataGridView1_CellValueChanged);
    DataGridView1.ColumnHeaderMouseClick += new DataGridViewCellMouseEventHandler(
        DataGridView1_ColumnHeaderMouseClick);
}
private void DataGridView1_ColumnHeaderMouseClick(object sender,
    DataGridViewCellMouseEventArgs e)
{
    DataGridViewColumn clickedColumn = DataGridView1.Columns[e.ColumnIndex];
    if (clickedColumn.SortMode != DataGridViewColumnSortMode.Automatic)
        this.SortRows(clickedColumn, true);
}
private void DataGridView1_RowsAdded(object sender,
    DataGridViewRowsAddedEventArgs e)
{
    this.SortRows(DataGridView1.SortedColumn, false);
}
private void DataGridView1_CellValueChanged(object sender,
    DataGridViewCellEventArgs e)
{
    if (DataGridView1.SortedColumn != null &&
        e.ColumnIndex == DataGridView1.SortedColumn.Index)
        this.SortRows(DataGridView1.SortedColumn, false);
}
private void SortRows(DataGridViewColumn sortColumn, bool orderToggle)
{
    if (sortColumn == null)
        return;
    if (sortColumn.SortMode == DataGridViewColumnSortMode.Programmatic &&
        DataGridView1.SortedColumn != null &&
        !DataGridView1.SortedColumn.Equals(sortColumn))
    {
        DataGridView1.SortedColumn.HeaderCell.SortGlyphDirection =
            SortOrder.None;
    }
    ListSortDirection sortDirection;
    if (orderToggle)
    {
        sortDirection =
            DataGridView1.SortOrder == SortOrder.Descending ?
            ListSortDirection.Ascending : ListSortDirection.Descending;
    }
    else
    {
        sortDirection =
            DataGridView1.SortOrder == SortOrder.Descending ?
            ListSortDirection.Descending : ListSortDirection.Ascending;
    }
    SortOrder sortOrder =
        sortDirection == ListSortDirection.Ascending ?
        SortOrder.Ascending : SortOrder.Descending;
    DataGridView1.Sort(sortColumn, sortDirection);
    if (sortColumn.SortMode == DataGridViewColumnSortMode.Programmatic)
    {
        sortColumn.HeaderCell.SortGlyphDirection = sortOrder;
    }
}

32. DataGridView指定列指定排序

[VB.NET]

vbnet 复制代码
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

[C#]

cs 复制代码
DataTable dt = (DataTable)DataGridView1.DataSource;
DataView dv = dt.DefaultView;
dv.Sort = "Column1, Column2 ASC";
DataGridView1.Columns["Column1"].HeaderCell.SortGlyphDirection =
    SortOrder.Ascending;
DataGridView1.Columns["Column2"].HeaderCell.SortGlyphDirection =
    SortOrder.Ascending;

33. DataGridView单元格样式设置

指定行列的样式设定

[VB.NET]

DataGridView1.Columns(0).DefaultCellStyle.BackColor = Color.Aqua

DataGridView1.Rows(0).DefaultCellStyle.BackColor = Color.LightGray

[C#]

DataGridView1.Columns[0].DefaultCellStyle.BackColor = Color.Aqua;

DataGridView1.Rows[0].DefaultCellStyle.BackColor = Color.LightGray;

奇数行样式设定

[VB.NET]

DataGridView1.AlternatingRowsDefaultCellStyle.BackColor = Color.GreenYellow

[C#]

DataGridView1.AlternatingRowsDefaultCellStyle.BackColor = Color.GreenYellow;

行,列表头部的样式设定

[VB.NET]

DataGridView1.ColumnHeadersDefaultCellStyle.BackColor = Color.Ivory

DataGridView1.RowHeadersDefaultCellStyle.BackColor = Color.Lime

[C#]

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

下例说明

[VB.NET]

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)

[C#]

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

复数行列的样式设定

[VB.NET]

vbnet 复制代码
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

[C#]

cs 复制代码
DataGridViewCellStyle cellStyle = new DataGridViewCellStyle();
cellStyle.BackColor = Color.Yellow;
for (int i = 0; i < DataGridView1.Columns.Count; i++)
{
    if (i % 2 == 0)
        DataGridView1.Columns[i].DefaultCellStyle = cellStyle;
}
for (int i = 0; i < DataGridView1.Columns.Count; i++)
{
    if (i % 2 == 0)
        DataGridView1.Columns[i].DefaultCellStyle.BackColor = Color.Yellow;
}

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

单元格的设定

[VB.NET]

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

[C#]

DataGridView1.Columns["Column1"].DefaultCellStyle.Alignment =DataGridViewContentAlignment.MiddleCenter;

表头的设定

[VB.NET]

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

[C#]

DataGridView1.Columns["Column1"].HeaderCell.Style.Alignment =DataGridViewContentAlignment.MiddleCenter;

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

[VB.NET]

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

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

[C#]

DataGridView1.Columns["Column1"].DefaultCellStyle.WrapMode =DataGridViewTriState.True;

DataGridView1.Columns["Column1"].HeaderCell.Style.WrapMode =DataGridViewTriState.True;

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

[VB.NET]

DataGridView1.DefaultCellStyle.NullValue = "(没有被指定)"

[C#]

DataGridView1.DefaultCellStyle.NullValue = "(没有被指定。)";

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

[VB.NET]

DataGridView1.DefaultCellStyle.NullValue = "-"

DataGridView1.DefaultCellStyle.DataSourceNullValue = "X"

[C#]

DataGridView1.DefaultCellStyle.NullValue = "-";

DataGridView1.DefaultCellStyle.DataSourceNullValue = "X";

37. DataGridView单元格样式格式化

[VB.NET]

DataGridView1.Columns(0).DefaultCellStyle.Format = "c"

DataGridView1.Columns(1).DefaultCellStyle.Format = "c"

DataGridView1.Columns(1).DefaultCellStyle.FormatProvider = New System.Globalization.CultureInfo("en-US")

[C#]

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 |

Format的参数一览(小数)

|---------------|---------------|------------------|
| 格式 | 説明 | 当值为"123456"时 |
| 没有格式 | 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指定单元格颜色设定

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

[VB.NET]

vbnet 复制代码
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

[C#]

cs 复制代码
private void DataGridView1_CellMouseEnter(object sender,
    DataGridViewCellEventArgs e)
{
    if (e.ColumnIndex >= 0 && e.RowIndex >= 0)
    {
        DataGridView dgv = (DataGridView)sender;
        dgv[e.ColumnIndex, e.RowIndex].Style.BackColor = Color.Red;
        dgv[e.ColumnIndex, e.RowIndex].Style.SelectionBackColor = Color.Red;
    }
}
private void DataGridView1_CellMouseLeave(object sender,
    DataGridViewCellEventArgs e)
{
    if (e.ColumnIndex >= 0 && e.RowIndex >= 0)
    {
        DataGridView dgv = (DataGridView)sender;
        dgv[e.ColumnIndex, e.RowIndex].Style.BackColor = Color.Empty;
dgv[e.ColumnIndex, e.RowIndex].Style.SelectionBackColor = Color.Empty;
    }
}

表头部单元格颜色设定

[VB.NET]

DataGridView1.ColumnHeadersDefaultCellStyle.BackColor = Color.Yellow

DataGridView1.RowHeadersDefaultCellStyle.BackColor = Color.YellowGreen

DataGridView1.TopLeftHeaderCell.Style.BackColor = Color.Blue

[C#]

DataGridView1.ColumnHeadersDefaultCellStyle.BackColor = Color.Yellow;

DataGridView1.RowHeadersDefaultCellStyle.BackColor = Color.YellowGreen;

DataGridView1.TopLeftHeaderCell.Style.BackColor = Color.Blue;

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

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

[VB.NET]

vbnet 复制代码
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

[C#]

cs 复制代码
private DataGridViewCellStyle defaultCellStyle;
private DataGridViewCellStyle mouseCellStyle;
private void Form1_Load(object sender, EventArgs e)
{
    this.defaultCellStyle = new DataGridViewCellStyle();
    this.mouseCellStyle = new DataGridViewCellStyle();
    this.mouseCellStyle.Font = new Font(DataGridView1.Font,
        DataGridView1.Font.Style | FontStyle.Bold);
}
private void DataGridView1_CellEnter(object sender,
    DataGridViewCellEventArgs e)
{
    if (e.ColumnIndex >= 0 && e.RowIndex >= 0)
    {
        DataGridView dgv = (DataGridView)sender;
        dgv[e.ColumnIndex, e.RowIndex].Style = this.mouseCellStyle;
    }
}
private void DataGridView1_CellLeave(object sender,
    DataGridViewCellEventArgs e)
{
    if (e.ColumnIndex >= 0 && e.RowIndex >= 0)
    {
        DataGridView dgv = (DataGridView)sender;
        dgv[e.ColumnIndex, e.RowIndex].Style = this.defaultCellStyle;
    }
}

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

单元格负数情况下显示黄色,0的情况下显示红色

[VB.NET]

vbnet 复制代码
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

[C#]

cs 复制代码
private void DataGridView1_CellFormatting(object sender,
    DataGridViewCellFormattingEventArgs e)
{
    DataGridView dgv = (DataGridView)sender;
    if (dgv.Columns[e.ColumnIndex].Name == "Column1" && e.Value is int)
    {
        int val = (int)e.Value;
        if (val < 0)
        {
            e.CellStyle.BackColor = Color.Yellow;
        }
        else if (val == 0)
        {
            e.CellStyle.BackColor = Color.Red;
        }
    }
}

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

[VB.NET]

vbnet 复制代码
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

[C#]

cs 复制代码
private void DataGridView1_CellPainting(object sender,
    DataGridViewCellPaintingEventArgs e)
{
    if (e.ColumnIndex >= 0 && e.RowIndex >= 0 &&
        (e.PaintParts & DataGridViewPaintParts.Background) ==
            DataGridViewPaintParts.Background)
    {
        Color bColor1, bColor2;
        if ((e.PaintParts & DataGridViewPaintParts.SelectionBackground) ==
                DataGridViewPaintParts.SelectionBackground &&
            (e.State & DataGridViewElementStates.Selected) ==
                DataGridViewElementStates.Selected)
        {
            bColor1 = e.CellStyle.SelectionBackColor;
            bColor2 = Color.Black;
        }
        else
        {
            bColor1 = e.CellStyle.BackColor;
            bColor2 = Color.LemonChiffon;
        }
        using (System.Drawing.Drawing2D.LinearGradientBrush b =
            new System.Drawing.Drawing2D.LinearGradientBrush(
            e.CellBounds, bColor1, bColor2,
            System.Drawing.Drawing2D.LinearGradientMode.Horizontal))
        {
            e.Graphics.FillRectangle(b, e.CellBounds);
        }
        DataGridViewPaintParts paintParts =
           e.PaintParts & ~DataGridViewPaintParts.Background;
        e.Paint(e.ClipBounds, paintParts);
        e.Handled = true;
    }
}

单元格背景显示图像

[VB.NET]

vbnet 复制代码
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

[C#]

cs 复制代码
private Bitmap cellBackImage = new Bitmap("C://back.gif");
private void DataGridView1_CellPainting(object sender,
    DataGridViewCellPaintingEventArgs e)
{
    if (e.ColumnIndex >= 0 && e.RowIndex >= 0 &&
        (e.PaintParts & DataGridViewPaintParts.Background) ==
            DataGridViewPaintParts.Background)
    {
        DataGridViewPaintParts backParts = e.PaintParts &
            (DataGridViewPaintParts.Background |
            DataGridViewPaintParts.SelectionBackground);
        e.Paint(e.ClipBounds, backParts);
        int x = e.CellBounds.X +
            (e.CellBounds.Width - cellBackImage.Width) / 2;
        int y = e.CellBounds.Y +
            (e.CellBounds.Height - cellBackImage.Height) / 2;
        e.Graphics.DrawImage(cellBackImage, x, y);
        DataGridViewPaintParts paintParts =
            e.PaintParts & ~backParts;
        e.Paint(e.ClipBounds, paintParts);
        e.Handled = true;
    }
}

42. DataGridView行样式描画

利用RowPostPaint事件描画

[VB.NET]

vbnet 复制代码
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

[C#]

cs 复制代码
private void DataGridView1_RowPostPaint(object sender,
    DataGridViewRowPostPaintEventArgs e)
{
    DataGridView dgv = (DataGridView)sender;
    Pen linePen;
    switch (e.RowIndex % 3)
    {
        case 0:
            linePen = Pens.Blue;
            break;
        case 1:
            linePen = Pens.Green;
            break;
        default:
            linePen = Pens.Red;
            break;
    }
    int startX = dgv.RowHeadersVisible ? dgv.RowHeadersWidth : 0;
    int startY = e.RowBounds.Top + e.RowBounds.Height - 1;
    int endX = startX + dgv.Columns.GetColumnsWidth(
        DataGridViewElementStates.Visible) -
        dgv.HorizontalScrollingOffset;
    e.Graphics.DrawLine(linePen,
        startX, startY, endX, startY);
}

利用RowPrePaint事件描画

[VB.NET]

vbnet 复制代码
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

[C#]

cs 复制代码
private void DataGridView1_RowPrePaint(object sender,
    DataGridViewRowPrePaintEventArgs e)
{
    if ((e.PaintParts & DataGridViewPaintParts.Background) ==
        DataGridViewPaintParts.Background)
    {
        Color bColor1, bColor2;
        if ((e.PaintParts & DataGridViewPaintParts.SelectionBackground) ==
                DataGridViewPaintParts.SelectionBackground &&
            (e.State & DataGridViewElementStates.Selected) ==
                DataGridViewElementStates.Selected)
        {
            bColor1 = e.InheritedRowStyle.SelectionBackColor;
            bColor2 = Color.Black;
        }
        else
        {
            bColor1 = e.InheritedRowStyle.BackColor;
            bColor2 = Color.YellowGreen;
        }
        DataGridView dgv = (DataGridView)sender;
        int rectLeft2 = dgv.RowHeadersVisible ? dgv.RowHeadersWidth : 0;
        int rectLeft = rectLeft2 - dgv.HorizontalScrollingOffset;
        int rectWidth = dgv.Columns.GetColumnsWidth(
            DataGridViewElementStates.Visible);
        Rectangle rect = new Rectangle(rectLeft, e.RowBounds.Top,
            rectWidth, e.RowBounds.Height - 1);
        using (System.Drawing.Drawing2D.LinearGradientBrush b =
            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);
        }
        e.PaintHeader(true);
        e.PaintParts &= ~DataGridViewPaintParts.Background;
    }
}
private void DataGridView1_ColumnWidthChanged(object sender,
    DataGridViewColumnEventArgs e)
{
    DataGridView dgv = (DataGridView)sender;
    dgv.Invalidate();
}

43. DataGridView显示行号

[VB.NET]

cs 复制代码
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

[C#]

cs 复制代码
private void DataGridView1_CellPainting(object sender,
    DataGridViewCellPaintingEventArgs e)
{
    if (e.ColumnIndex < 0 && e.RowIndex >= 0)
    {
        e.Paint(e.ClipBounds, DataGridViewPaintParts.All);
        Rectangle indexRect = e.CellBounds;
        indexRect.Inflate(-2, -2);
        TextRenderer.DrawText(e.Graphics,
            (e.RowIndex + 1).ToString(),
            e.CellStyle.Font,
            indexRect,
            e.CellStyle.ForeColor,
            TextFormatFlags.Right | TextFormatFlags.VerticalCenter);
        e.Handled = true;
    }
}

利用RowPostPaint事件描画

[VB.NET]

vbnet 复制代码
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

[C#]

cs 复制代码
private void DataGridView1_RowPostPaint(object sender,
    DataGridViewRowPostPaintEventArgs e)
{
    DataGridView dgv = (DataGridView)sender;
    if (dgv.RowHeadersVisible)
    {
        Rectangle rect = 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 | TextFormatFlags.VerticalCenter);
    }
}

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

[VB.NET]

vbnet 复制代码
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

[C#]

cs 复制代码
private void DataGridView1_CellPainting(object sender,
    DataGridViewCellPaintingEventArgs e)
{
    if (e.ColumnIndex >= 0 && e.RowIndex >= 0)
    {
        DataGridViewPaintParts paintParts =
            e.PaintParts & ~DataGridViewPaintParts.Focus;
        e.Paint(e.ClipBounds, paintParts);
        e.Handled = true;
    }
}

利用RowPrePaint事件实现

[VB.NET]

vbnet 复制代码
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

[C#]

cs 复制代码
private void DataGridView1_RowPrePaint(object sender,
    DataGridViewRowPrePaintEventArgs e)
{
    e.PaintParts &= ~DataGridViewPaintParts.Focus;
}

45. DataGridView列中显示选择框CheckBox

[VB.NET]

'添加CheckBox列

Dim column As New DataGridViewCheckBoxColumn

DataGridView1.Columns.Add(column)

[C#]

//添加CheckBox列

DataGridViewCheckBoxColumn column = new DataGridViewCheckBoxColumn();

DataGridView1.Columns.Add(column);

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

[VB.NET]

'能够显示3种检查状态

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

column.ThreeState = True

[C#]

DataGridViewCheckBoxColumn column =(DataGridViewCheckBoxColumn)DataGridView1.Columns[0];

column.ThreeState = true;

46. DataGridView中显示下拉框ComboBox

[VB.NET]

vbnet 复制代码
Dim column As New DataGridViewComboBoxColumn()
'在ComboBox的列表中指定要显示的项目
column.Items.Add("日曜日")
column.Items.Add("月曜日")
column.Items.Add("火曜日")
column.Items.Add("水曜日")
column.Items.Add("木曜日")
column.Items.Add("金曜日")
column.Items.Add("土曜日")
'"Week"显示绑定在列中的数据
column.DataPropertyName = "Week"
DataGridView1.Columns.Insert(DataGridView1.Columns("Week").Index, column)
DataGridView1.Columns.Remove("Week")
column.Name = "Week"

[C#]

cs 复制代码
DataGridViewComboBoxColumn column = new DataGridViewComboBoxColumn();
//显示绑定在列中的数据
column.Items.Add("日曜日");
column.Items.Add("月曜日");
column.Items.Add("火曜日");
column.Items.Add("水曜日");
column.Items.Add("木曜日");
column.Items.Add("金曜日");
column.Items.Add("土曜日");
//"Week"显示绑定在列中的数据
column.DataPropertyName = "Week";
DataGridView1.Columns.Insert(DataGridView1.Columns["Week"].Index, column);
DataGridView1.Columns.Remove("Week");
column.Name = "Week";

通过列Data绑定设置ComboBox

[VB.NET]

vbnet 复制代码
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"
'DataGridViewComboBoxColumnのDataSourceを設定
column.DataSource = weekTable
column.ValueMember = "Value"
column.DisplayMember = "Display"
DataGridView1.Columns.Add(column)

[C#]

cs 复制代码
DataTable weekTable = new DataTable("WeekTable");
weekTable.Columns.Add("Display", typeof(string));
weekTable.Columns.Add("Value", typeof(int));
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);
DataGridViewComboBoxColumn column = new DataGridViewComboBoxColumn();
column.DataPropertyName = "Week";
column.DataSource = weekTable;
column.ValueMember = "Value";
column.DisplayMember = "Display";
DataGridView1.Columns.Add(column);

默认状态下,所有下拉框都显示;DisplayStyleForCurrentCellOnly=True的状态下,当前的单元格显示下拉框,其余不显示;还有一种就是光标移动时强调显示。如下图左中右三列。

47. DataGridView单击打开下拉框

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

[VB.NET]

vbnet 复制代码
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

[C#]

cs 复制代码
private void DataGridView1_CellEnter(object sender,
    DataGridViewCellEventArgs e)
{
    DataGridView dgv = (DataGridView)sender;
    if (dgv.Columns[e.ColumnIndex].Name == "ComboBox" &&
       dgv.Columns[e.ColumnIndex] is DataGridViewComboBoxColumn)
    {
        SendKeys.Send("{F4}");
    }
}

48. DataGridView中显示按钮

[VB.NET]

vbnet 复制代码
Dim column As New DataGridViewButtonColumn()
column.Name = "Button"
column.UseColumnTextForButtonValue = True
column.Text = "详细阅读"
DataGridView1.Columns.Add(column)

[C#]

cs 复制代码
DataGridViewButtonColumn column = new DataGridViewButtonColumn();
column.Name = "Button";
column.UseColumnTextForButtonValue = true;
column.Text = "详细阅读";
DataGridView1.Columns.Add(column);

按钮按下事件取得

[VB.NET]

cs 复制代码
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

[C#]

cs 复制代码
private void DataGridView1_CellContentClick(object sender,
    DataGridViewCellEventArgs e)
{
    DataGridView dgv = (DataGridView)sender;
    if (dgv.Columns[e.ColumnIndex].Name == "Button")
    {
        MessageBox.Show(e.RowIndex.ToString() +
            "行按钮被点击了。");
    }
}

49. DataGridView中显示链接

[VB.NET]

Dim column As New DataGridViewLinkColumn()

column.Name = "Link"

column.UseColumnTextForLinkValue = True

column.Text = "详细阅读"

column.LinkBehavior = LinkBehavior.HoverUnderline

column.TrackVisitedState = True

DataGridView1.Columns.Add(column)

[C#]

DataGridViewLinkColumn column = new DataGridViewLinkColumn();

column.Name = "Link";

column.UseColumnTextForLinkValue = true;

column.Text = "详细阅读";

column.LinkBehavior = LinkBehavior.HoverUnderline;

column.TrackVisitedState = true;

DataGridView1.Columns.Add(column);

链接按下事件取得

[VB.NET]

vbnet 复制代码
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

[C#]

vbnet 复制代码
private void DataGridView1_CellContentClick(object sender,
    DataGridViewCellEventArgs e)
{
    DataGridView dgv = (DataGridView)sender;
    if (dgv.Columns[e.ColumnIndex].Name == "Link")
    {
        MessageBox.Show(e.RowIndex.ToString() +
            "行按钮被点击了。");
        DataGridViewLinkCell cell =
            (DataGridViewLinkCell)dgv[e.ColumnIndex, e.RowIndex];
        cell.LinkVisited = true;
    }
}

50. DataGridView中显示图像

[VB.NET]

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") '

[C#]

DataGridViewImageColumn column = 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");

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

[VB.NET]

Dim imageColumn As DataGridViewImageColumn = _

CType(DataGridView1.Columns("Image"), DataGridViewImageColumn)

imageColumn.DefaultCellStyle.NullValue = Nothing

[C#]

DataGridViewImageColumn imageColumn =

(DataGridViewImageColumn)DataGridView1.Columns["Image"];

imageColumn.DefaultCellStyle.NullValue = null;

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

[VB.NET]

vbnet 复制代码
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

[C#]

cs 复制代码
private void DataGridView1_EditingControlShowing(object sender,
    DataGridViewEditingControlShowingEventArgs e)
{
    if (e.Control is DataGridViewTextBoxEditingControl)
    {
        DataGridView dgv = (DataGridView)sender;
        DataGridViewTextBoxEditingControl tb =
            (DataGridViewTextBoxEditingControl)e.Control;
        if (dgv.CurrentCell.OwningColumn.Name == "Column1")
            tb.ImeMode = ImeMode.Disable;
        else
            tb.ImeMode = dgv.ImeMode;
    }
}

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

52. DataGridView输入自动完成

[VB.NET]

vbnet 复制代码
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

[C#]

cs 复制代码
AutoCompleteStringCollection autoCompleteSource =
    new AutoCompleteStringCollection();
private void DataGridView1_EditingControlShowing(object sender,
    DataGridViewEditingControlShowingEventArgs e)
{
    DataGridView dgv = (DataGridView)sender;
    if (e.Control is TextBox)
    {
        TextBox tb = (TextBox)e.Control;
        if (dgv.CurrentCell.OwningColumn.Name == "Column1")
        {
            tb.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
            tb.AutoCompleteSource = AutoCompleteSource.CustomSource;
            tb.AutoCompleteCustomSource = this.autoCompleteSource;
        }
        else
        {
            tb.AutoCompleteMode = AutoCompleteMode.None;
        }
    }
}
private void DataGridView1_DataSourceChanged(object sender, EventArgs e)
{
    DataGridView dgv = (DataGridView)sender;
    this.autoCompleteSource.Clear();
    foreach (DataGridViewRow r in dgv.Rows)
    {
        string val = r.Cells["Column1"].Value as string;
        if (!string.IsNullOrEmpty(val) &&
            !this.autoCompleteSource.Contains(val))
        {
            autoCompleteSource.Add(val);
        }
    }
}
private void DataGridView1_CellValueChanged(object sender,
    DataGridViewCellEventArgs e)
{
    DataGridView dgv = (DataGridView)sender;
    if (dgv.Columns[e.ColumnIndex].Name == "Column1")
    {
        string val = dgv[e.ColumnIndex, e.RowIndex].Value as string;
        if (!string.IsNullOrEmpty(val) &&
            !this.autoCompleteSource.Contains(val))
        {
            autoCompleteSource.Add(val);
        }
    }
}

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

[VB.NET]

cs 复制代码
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​​​​​​​

[C#]

cs 复制代码
private void DataGridView1_EditingControlShowing(object sender,
    DataGridViewEditingControlShowingEventArgs e)
{
    if (e.Control is DataGridViewTextBoxEditingControl)
    {
        DataGridView dgv = (DataGridView)sender;
        DataGridViewTextBoxEditingControl tb =
            (DataGridViewTextBoxEditingControl)e.Control;
        tb.KeyPress -=
            new KeyPressEventHandler(dataGridViewTextBox_KeyPress);
        if (dgv.CurrentCell.OwningColumn.Name == "Column1")
        {
            tb.KeyPress +=
                new KeyPressEventHandler(dataGridViewTextBox_KeyPress);
        }
    }
}
private void dataGridViewTextBox_KeyPress(object sender,
    KeyPressEventArgs e)
{
    if (e.KeyChar < '0' || e.KeyChar > '9')
    {
        e.Handled = true;
    }
}

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

[VB.NET]

vbnet 复制代码
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

[C#]

cs 复制代码
private DataGridViewComboBoxEditingControl dataGridViewComboBox = null;
private void DataGridView1_EditingControlShowing(object sender,
    DataGridViewEditingControlShowingEventArgs e)
{
    if (e.Control is DataGridViewComboBoxEditingControl)
    {
        DataGridView dgv = (DataGridView)sender;
        if (dgv.CurrentCell.OwningColumn.Name == "ComboBox")
        {
            this.dataGridViewComboBox =
                (DataGridViewComboBoxEditingControl)e.Control;
            this.dataGridViewComboBox.SelectedIndexChanged +=
                new EventHandler(dataGridViewComboBox_SelectedIndexChanged);
        }
    }
}
private void DataGridView1_CellEndEdit(object sender,
    DataGridViewCellEventArgs e)
{
    if (this.dataGridViewComboBox != null)
    {
        this.dataGridViewComboBox.SelectedIndexChanged -=
            new EventHandler(dataGridViewComboBox_SelectedIndexChanged);
        this.dataGridViewComboBox = null;
    }
}
private void dataGridViewComboBox_SelectedIndexChanged(object sender,
    EventArgs e)
{
    DataGridViewComboBoxEditingControl cb =
        (DataGridViewComboBoxEditingControl)sender;
    Console.WriteLine(cb.SelectedItem);
}

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

[VB.NET]

vbnet 复制代码
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

[C#]

cs 复制代码
private void DataGridView1_EditingControlShowing(object sender,
    DataGridViewEditingControlShowingEventArgs e)
{
    if (e.Control is DataGridViewComboBoxEditingControl)
    {
        DataGridView dgv = (DataGridView)sender;
        if (dgv.CurrentCell.OwningColumn.Name == "ComboBox")
        {
            DataGridViewComboBoxEditingControl cb =
                (DataGridViewComboBoxEditingControl)e.Control;
            cb.DropDownStyle = ComboBoxStyle.DropDown;
        }
    }
}
private void DataGridView1_CellValidating(object sender,
    DataGridViewCellValidatingEventArgs e)
{
    DataGridView dgv = (DataGridView)sender;
    if (dgv.Columns[e.ColumnIndex].Name == "ComboBox" &&
        dgv.Columns[e.ColumnIndex] is DataGridViewComboBoxColumn)
    {
        DataGridViewComboBoxColumn cbc =
            (DataGridViewComboBoxColumn)dgv.Columns[e.ColumnIndex];
        if (!cbc.Items.Contains(e.FormattedValue))
        {
            cbc.Items.Add(e.FormattedValue);
        }
    }
}

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

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

[VB.NET]

vbnet 复制代码
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

[C#]

cs 复制代码
using System;
using System.Drawing;
using System.Windows.Forms;

public class DataGridViewProgressBarColumn : DataGridViewTextBoxColumn
{
    public DataGridViewProgressBarColumn()
    {
        this.CellTemplate = new DataGridViewProgressBarCell();
    }
    public override DataGridViewCell CellTemplate
    {
        get
        {
            return base.CellTemplate;
        }
        set
        {
            if (!(value is DataGridViewProgressBarCell))
            {
                throw new InvalidCastException(
                    "DataGridViewProgressBarCellオブジェクトを" +
                    "指定してください。");
            }
            base.CellTemplate = value;
        }
    }

    public int Maximum
    {
        get
        {
            return ((DataGridViewProgressBarCell)this.CellTemplate).Maximum;
        }
        set
        {
            if (this.Maximum == value)
                return;
            ((DataGridViewProgressBarCell)this.CellTemplate).Maximum =
                value;
            if (this.DataGridView == null)
                return;
            int rowCount = this.DataGridView.RowCount;
            for (int i = 0; i < rowCount; i++)
            {
                DataGridViewRow r = this.DataGridView.Rows.SharedRow(i);
                ((DataGridViewProgressBarCell)r.Cells[this.Index]).Maximum =
                    value;
            }
        }
    }
    public int Mimimum
    {
        get
        {
            return ((DataGridViewProgressBarCell)this.CellTemplate).Mimimum;
        }
        set
        {
            if (this.Mimimum == value)
                return;
            ((DataGridViewProgressBarCell)this.CellTemplate).Mimimum =
                value;
            if (this.DataGridView == null)
                return;
            int rowCount = this.DataGridView.RowCount;
            for (int i = 0; i < rowCount; i++)
            {
                DataGridViewRow r = this.DataGridView.Rows.SharedRow(i);
                ((DataGridViewProgressBarCell)r.Cells[this.Index]).Mimimum =
                    value;
            }
        }
    }
}

public class DataGridViewProgressBarCell : DataGridViewTextBoxCell
{

    public DataGridViewProgressBarCell()
    {
        this.maximumValue = 100;
        this.mimimumValue = 0;
    }
    private int maximumValue;
    public int Maximum
    {
        get
        {
            return this.maximumValue;
        }
        set
        {
            this.maximumValue = value;
        }
    }
    private int mimimumValue;
    public int Mimimum
    {
        get
        {
            return this.mimimumValue;
        }
        set
        {
            this.mimimumValue = value;
        }
    }

    public override Type ValueType
    {
        get
        {
            return typeof(int);
        }
    }
    public override object DefaultNewRowValue
    {
        get
        {
            return 0;
        }
    }
    public override object Clone()
    {
        DataGridViewProgressBarCell cell =
            (DataGridViewProgressBarCell)base.Clone();
        cell.Maximum = this.Maximum;
        cell.Mimimum = this.Mimimum;
        return cell;
    }
    protected override void Paint(Graphics graphics,
        Rectangle clipBounds, Rectangle cellBounds,
        int rowIndex, DataGridViewElementStates cellState,
        object value, object formattedValue, string errorText,
        DataGridViewCellStyle cellStyle,
        DataGridViewAdvancedBorderStyle advancedBorderStyle,
        DataGridViewPaintParts paintParts)
    {
        int intValue = 0;
        if (value is int)
            intValue = (int)value;
        if (intValue < this.mimimumValue)
            intValue = this.mimimumValue;
        if (intValue > this.maximumValue)
            intValue = this.maximumValue;
        double rate = (double)(intValue - this.mimimumValue) /
            (this.maximumValue - this.mimimumValue);
        if ((paintParts & DataGridViewPaintParts.Border) ==
            DataGridViewPaintParts.Border)
        {
            this.PaintBorder(graphics, clipBounds, cellBounds,
                cellStyle, advancedBorderStyle);
        }
        Rectangle borderRect = this.BorderWidths(advancedBorderStyle);
        Rectangle paintRect = new Rectangle(
            cellBounds.Left + borderRect.Left,
            cellBounds.Top + borderRect.Top,
            cellBounds.Width - borderRect.Right,
            cellBounds.Height - borderRect.Bottom);
        bool isSelected =
            (cellState & DataGridViewElementStates.Selected) ==
            DataGridViewElementStates.Selected;
        Color bkColor;
        if (isSelected &&
            (paintParts & DataGridViewPaintParts.SelectionBackground) ==
                DataGridViewPaintParts.SelectionBackground)
        {
            bkColor = cellStyle.SelectionBackColor;
        }
        else
        {
            bkColor = cellStyle.BackColor;
        }
        if ((paintParts & DataGridViewPaintParts.Background) ==
            DataGridViewPaintParts.Background)
        {
            using (SolidBrush backBrush = new SolidBrush(bkColor))
            {
                graphics.FillRectangle(backBrush, paintRect);
            }
        }
        paintRect.Offset(cellStyle.Padding.Right, cellStyle.Padding.Top);
        paintRect.Width -= cellStyle.Padding.Horizontal;
        paintRect.Height -= cellStyle.Padding.Vertical;
        if ((paintParts & DataGridViewPaintParts.ContentForeground) ==
            DataGridViewPaintParts.ContentForeground)
        {
            if (ProgressBarRenderer.IsSupported)
            {
                ProgressBarRenderer.DrawHorizontalBar(graphics, paintRect);
                Rectangle barBounds = new Rectangle(
                    paintRect.Left + 3, paintRect.Top + 3,
                    paintRect.Width - 4, paintRect.Height - 6);
                barBounds.Width = (int)Math.Round(barBounds.Width * rate);
                ProgressBarRenderer.DrawHorizontalChunks(graphics, barBounds);
            }
            else
            {
                graphics.FillRectangle(Brushes.White, paintRect);
                graphics.DrawRectangle(Pens.Black, paintRect);
                Rectangle barBounds = new Rectangle(
                    paintRect.Left + 1, paintRect.Top + 1,
                    paintRect.Width - 1, paintRect.Height - 1);
                barBounds.Width = (int)Math.Round(barBounds.Width * rate);
                graphics.FillRectangle(Brushes.Blue, barBounds);
            }
        }
        if (this.DataGridView.CurrentCellAddress.X == this.ColumnIndex &&
            this.DataGridView.CurrentCellAddress.Y == this.RowIndex &&
            (paintParts & DataGridViewPaintParts.Focus) ==
                DataGridViewPaintParts.Focus &&
            this.DataGridView.Focused)
        {
            Rectangle focusRect = paintRect;
            focusRect.Inflate(-3, -3);
            ControlPaint.DrawFocusRectangle(graphics, focusRect);
        }
        if ((paintParts & DataGridViewPaintParts.ContentForeground) ==
            DataGridViewPaintParts.ContentForeground)
        {
            string txt = string.Format("{0}%", Math.Round(rate * 100));
            TextFormatFlags flags = TextFormatFlags.HorizontalCenter |
                TextFormatFlags.VerticalCenter;
            Color fColor = cellStyle.ForeColor;
            paintRect.Inflate(-2, -2);
            TextRenderer.DrawText(graphics, txt, cellStyle.Font,
                paintRect, fColor, flags);
        }
        if ((paintParts & DataGridViewPaintParts.ErrorIcon) ==
            DataGridViewPaintParts.ErrorIcon &&
            this.DataGridView.ShowCellErrors &&
            !string.IsNullOrEmpty(errorText))
        {
            Rectangle iconBounds = this.GetErrorIconBounds(
                graphics, cellStyle, rowIndex);
            iconBounds.Offset(cellBounds.X, cellBounds.Y);
            this.PaintErrorIcon(graphics, iconBounds, cellBounds, errorText);
        }
    }
}

用法如下

[VB.NET]

Dim pbColumn As New DataGridViewProgressBarColumn()

pbColumn.DataPropertyName = "Column1"

DataGridView1.Columns.Add(pbColumn)

[C#]

DataGridViewProgressBarColumn pbColumn =

new DataGridViewProgressBarColumn();

pbColumn.DataPropertyName = "Column1";

DataGridView1.Columns.Add(pbColumn);

58. DataGridView中添加MaskedTextBox

[VB.NET]

vbnet 复制代码
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

[C#]

cs 复制代码
using System;
using System.Windows.Forms;

public class DataGridViewMaskedTextBoxColumn :
    DataGridViewColumn
{
    public DataGridViewMaskedTextBoxColumn()
        : base(new DataGridViewMaskedTextBoxCell())
    {
    }
    private string maskValue = "";

    public string Mask
    {
        get
        {
            return this.maskValue;
        }
        set
        {
            this.maskValue = value;
        }
    }

    public override object Clone()
    {
        DataGridViewMaskedTextBoxColumn col =
            (DataGridViewMaskedTextBoxColumn)base.Clone();
        col.Mask = this.Mask;
        return col;
    }
    public override DataGridViewCell CellTemplate
    {
        get
        {
            return base.CellTemplate;
        }
        set
        {
            if (!(value is DataGridViewMaskedTextBoxCell))
            {
                throw new InvalidCastException(
                    "DataGridViewMaskedTextBoxCellオブジェクトを" +
                    "指定してください。");
            }
            base.CellTemplate = value;
        }
    }
}

public class DataGridViewMaskedTextBoxCell :
    DataGridViewTextBoxCell
{
    public DataGridViewMaskedTextBoxCell()
    {
    }
    public override void InitializeEditingControl(
        int rowIndex, object initialFormattedValue,
        DataGridViewCellStyle dataGridViewCellStyle)
    {
        base.InitializeEditingControl(rowIndex,
            initialFormattedValue, dataGridViewCellStyle);
        DataGridViewMaskedTextBoxEditingControl maskedBox =
            this.DataGridView.EditingControl as
            DataGridViewMaskedTextBoxEditingControl;
        if (maskedBox != null)
        {
            maskedBox.Text =
                this.Value != null ? this.Value.ToString() : "";
            DataGridViewMaskedTextBoxColumn column =
                this.OwningColumn as DataGridViewMaskedTextBoxColumn;
            if (column != null)
            {
                maskedBox.Mask = column.Mask;
            }
        }
    }
    public override Type EditType
    {
        get
        {
            return typeof(DataGridViewMaskedTextBoxEditingControl);
        }
    }
    public override Type ValueType
    {
        get
        {
            return typeof(object);
        }
    }
    public override object DefaultNewRowValue
    {
        get
        {
            return base.DefaultNewRowValue;
        }
    }
}

public class DataGridViewMaskedTextBoxEditingControl :
    MaskedTextBox, IDataGridViewEditingControl
{
    DataGridView dataGridView;
    int rowIndex;
    bool valueChanged;
    public DataGridViewMaskedTextBoxEditingControl()
    {
        this.TabStop = false;
    }
    #region IDataGridViewEditingControl メンバ
    public object GetEditingControlFormattedValue(
        DataGridViewDataErrorContexts context)
    {
        return this.Text;
    }
    public object EditingControlFormattedValue
    {
        get
        {
            return this.GetEditingControlFormattedValue(
                DataGridViewDataErrorContexts.Formatting);
        }
        set
        {
            this.Text = (string)value;
        }
    }
    public void ApplyCellStyleToEditingControl(
        DataGridViewCellStyle dataGridViewCellStyle)
    {
        this.Font = dataGridViewCellStyle.Font;
        this.ForeColor = dataGridViewCellStyle.ForeColor;
        this.BackColor = dataGridViewCellStyle.BackColor;
        switch (dataGridViewCellStyle.Alignment)
        {
            case DataGridViewContentAlignment.BottomCenter:
            case DataGridViewContentAlignment.MiddleCenter:
            case DataGridViewContentAlignment.TopCenter:
                this.TextAlign = HorizontalAlignment.Center;
                break;
            case DataGridViewContentAlignment.BottomRight:
            case DataGridViewContentAlignment.MiddleRight:
            case DataGridViewContentAlignment.TopRight:
                this.TextAlign = HorizontalAlignment.Right;
                break;
            default:
                this.TextAlign = HorizontalAlignment.Left;
                break;
        }
    }
    public DataGridView EditingControlDataGridView
    {
        get
        {
            return this.dataGridView;
        }
        set
        {
            this.dataGridView = value;
        }
    }
    public int EditingControlRowIndex
    {
        get
        {
            return this.rowIndex;
        }
        set
        {
            this.rowIndex = value;
        }
    }
    public bool EditingControlValueChanged
    {
        get
        {
            return this.valueChanged;
        }
        set
        {
            this.valueChanged = value;
        }
    }
    public bool EditingControlWantsInputKey(
        Keys keyData, bool dataGridViewWantsInputKey)
    {
        switch (keyData & Keys.KeyCode)
        {
            case Keys.Right:
            case Keys.End:
            case Keys.Left:
            case Keys.Home:
                return true;
            default:
                return false;
        }
    }
    public Cursor EditingPanelCursor
    {
        get
        {
            return base.Cursor;
        }
    }
    public void PrepareEditingControlForEdit(bool selectAll)
    {
        if (selectAll)
        {
            this.SelectAll();
        }
        else
        {
            this.SelectionStart = this.TextLength;
        }
    }
    public bool RepositionEditingControlOnValueChange
    {
        get
        {
            return false;
        }
    }
    #endregion
    protected override void OnTextChanged(EventArgs e)
    {
        base.OnTextChanged(e);
        this.valueChanged = true;
        this.dataGridView.NotifyCurrentCellDirty(true);
    }
}

用法如下

[VB.NET]

Dim maskedColumn As New DataGridViewMaskedTextBoxColumn()

maskedColumn.DataPropertyName = "Column1"

maskedColumn.Mask = "000"

DataGridView1.Columns.Add(maskedColumn)

[C#]

DataGridViewMaskedTextBoxColumn maskedColumn =

new DataGridViewMaskedTextBoxColumn();

maskedColumn.DataPropertyName = "Column1";

maskedColumn.Mask = "000";

DataGridView1.Columns.Add(maskedColumn);

[VB.NET]

vbnet 复制代码
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

[C#]

cs 复制代码
using System;
using System.ComponentModel;
using System.Windows.Forms;

public class DataGridViewErrorIconColumn : DataGridViewImageColumn
{
    public DataGridViewErrorIconColumn()
    {
        this.CellTemplate = new DataGridViewErrorIconCell();
        this.ValueType = this.CellTemplate.ValueType;
    }
}

public class DataGridViewErrorIconCell : DataGridViewImageCell
{
    public DataGridViewErrorIconCell()
    {
        this.ValueType = typeof(int);
    }
    protected override object GetFormattedValue(
        object value, int rowIndex,
        ref DataGridViewCellStyle cellStyle,
        TypeConverter valueTypeConverter,
        TypeConverter formattedValueTypeConverter,
        DataGridViewDataErrorContexts context)
    {
        switch ((int)value)
        {
            case 1:
                return SystemIcons.Information;
            case 2:
                return SystemIcons.Warning;
            case 3:
                return SystemIcons.Error;
            default:
                return null;
        }
    }
    public override object DefaultNewRowValue
    {
        get
        {
            return 0;
        }
    }
}

用法如下

[VB.NET]

Dim iconColumn As New DataGridViewErrorIconColumn()

iconColumn.DataPropertyName = "Column1"

DataGridView1.Columns.Add(iconColumn)

[C#]

DataGridViewErrorIconColumn iconColumn =

new DataGridViewErrorIconColumn();

iconColumn.DataPropertyName = "Column1";

DataGridView1.Columns.Add(iconColumn);

相关推荐
军训猫猫头2 小时前
20.抽卡只有金,带保底(WPF) C#
ui·c#·wpf
明耀2 小时前
WPF 设置平均布局 如果隐藏的话,能够自动扩展
wpf
向宇it12 小时前
【从零开始入门unity游戏开发之——C#篇25】C#面向对象动态多态——virtual、override 和 base 关键字、抽象类和抽象方法
java·开发语言·unity·c#·游戏引擎
数据的世界0112 小时前
.NET开发人员学习书籍推荐
学习·.net
向宇it13 小时前
【从零开始入门unity游戏开发之——C#篇24】C#面向对象继承——万物之父(object)、装箱和拆箱、sealed 密封类
java·开发语言·unity·c#·游戏引擎
paixiaoxin14 小时前
CV-OCR经典论文解读|An Empirical Study of Scaling Law for OCR/OCR 缩放定律的实证研究
人工智能·深度学习·机器学习·生成对抗网络·计算机视觉·ocr·.net
晚安苏州14 小时前
WPF DataTemplate 数据模板
wpf
坐井观老天18 小时前
在C#中使用资源保存图像和文本和其他数据并在运行时加载
开发语言·c#
pchmi20 小时前
C# OpenCV机器视觉:模板匹配
opencv·c#·机器视觉
黄油饼卷咖喱鸡就味增汤拌孜然羊肉炒饭1 天前
C#都可以找哪些工作?
开发语言·c#