DataGridView用法合集【精品】

2024-09-04 14:12

本文主要是介绍DataGridView用法合集【精品】,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

目录

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

2.DataGridView编辑属性

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

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

5. DataGridView删除行可否设定

6. DataGridView行列不表示和删除

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

8. DataGridView行高列幅自动调整

9. DataGridView指定行列冻结

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

11. DataGridView行复数选择

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

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

14. DataGridView表头部单元格取得

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

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

17.DataGridView粘贴

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

19.DataGridView中的ContextMenuStrip属性

20. DataGridView指定滚动框位置

21. DataGridView手动追加列

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

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

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

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

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

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

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

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

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

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

32. DataGridView指定列指定排序

 33. DataGridView单元格样式设置

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

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

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

37. DataGridView单元格样式格式化

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

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

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

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

42. DataGridView行样式描画

43. DataGridView显示行号

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

45. DataGridView列中显示选择框CheckBox

46. DataGridView中显示下拉框ComboBox

47. DataGridView单击打开下拉框

48. DataGridView中显示按钮

49. DataGridView中显示链接

50. DataGridView中显示图像

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

52. DataGridView输入自动完成

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

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

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

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

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

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]

Private Sub DataGridView1_CellBeginEdit(ByVal sender As Object, _ByVal e As DataGridViewCellCancelEventArgs) _Handles DataGridView1.CellBeginEditDim dgv As DataGridView = CType(sender, DataGridView)If dgv.Columns(e.ColumnIndex).Name = "Column1" AndAlso _Not CBool(dgv("Column2", e.RowIndex).Value) Thene.Cancel = TrueEnd If
End Sub

[C#]

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]

If DataGridView1.CurrentRow.IsNewRow ThenConsole.WriteLine("现在的单元格所在的行是新的行")
ElseConsole.WriteLine("当前单元格所在的行不是新的行。")
End If

[C#]

if (DataGridView1.CurrentRow.IsNewRow)Console.WriteLine("现在的单元格所在的行是新的行");
elseConsole.WriteLine("当前单元格所在的行不是新的行");

5. DataGridView删除行可否设定

[VB.NET]

DataGridView1.AllowUserToDeleteRows = False

[C#]

DataGridView1.AllowUserToDeleteRows = false;

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

[VB.NET]

Private Sub DataGridView1_UserDeletingRow(ByVal sender As Object, _ByVal e As DataGridViewRowCancelEventArgs) _Handles DataGridView1.UserDeletingRowIf MessageBox.Show("要删除这一列吗?", "删除确认",MessageBoxButtons.OKCancel,MessageBoxIcon.Question) <> Windows.Forms.DialogResult.OK Thene.Cancel = TrueEnd If
End Sub

[C#]

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]

Dim r As DataGridViewRow
For Each r In DataGridView1.SelectedRowsIf Not r.IsNewRow ThenDataGridView1.Rows.Remove(r)End If
Next r

[C#]

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]

DataGridView1.ColumnHeadersHeightSizeMode =DataGridViewColumnHeadersHeightSizeMode.DisableResizing
DataGridView1.RowHeadersWidthSizeMode = DataGridViewRowHeadersWidthSizeMode.EnableResizing

[C#]

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]

For Each c As DataGridViewCell In DataGridView1.SelectedCellsConsole.WriteLine("{0}, {1}", c.ColumnIndex, c.RowIndex)
Next c
For Each r As DataGridViewRow In DataGridView1.SelectedRowsConsole.WriteLine(r.Index)
Next r
For Each c As DataGridViewColumn In DataGridView1.SelectedColumnsConsole.WriteLine(c.Index)
Next c

[C#]

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]

Dim i As Integer
For i = 0 To DataGridView1.Rows.Count - 1DataGridView1.Rows(i).HeaderCell.Value = i.ToString()
Next i
DataGridView1.AutoResizeRowHeadersWidth(DataGridViewRowHeadersWidthSizeMode.AutoSizeToAllHeaders)

[C#]

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]

If DataGridView1.CurrentCell Is Nothing ThenReturn
End If
Dim insertRowIndex As Integer = DataGridView1.CurrentCell.RowIndex
Dim pasteText As String = Clipboard.GetText()
If String.IsNullOrEmpty(pasteText) ThenReturn
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 linesIf isHeader ThenisHeader = FalseElseDim vals As String() = line.Split(ControlChars.Tab)If vals.Length - 1 <> DataGridView1.ColumnCount ThenThrow New ApplicationException("列数が違います。")End IfDim row As DataGridViewRow = DataGridView1.Rows(insertRowIndex)row.HeaderCell.Value = vals(0)Dim i As IntegerFor i = 0 To row.Cells.Count - 1row.Cells(i).Value = vals((i + 1))Next iinsertRowIndex += 1End If
Next line

[C#]

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]

Private Sub DataGridView1_CellToolTipTextNeeded(ByVal sender As Object, _ByVal e As DataGridViewCellToolTipTextNeededEventArgs) _Handles DataGridView1.CellToolTipTextNeedede.ToolTipText = e.ColumnIndex.ToString() + ", " + e.RowIndex.ToString()
End Sub

[C#]

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]

Private Sub DataGridView1_CellContextMenuStripNeeded( _ByVal sender As Object, _ByVal e As DataGridViewCellContextMenuStripNeededEventArgs) _Handles DataGridView1.CellContextMenuStripNeededDim dgv As DataGridView = CType(sender, DataGridView)If e.RowIndex < 0 Thene.ContextMenuStrip = Me.ContextMenuStrip1ElseIf e.ColumnIndex < 0 Thene.ContextMenuStrip = Me.ContextMenuStrip2ElseIf TypeOf (dgv(e.ColumnIndex, e.RowIndex).Value) Is Integer Thene.ContextMenuStrip = Me.ContextMenuStrip3End If
End Sub

[C#]

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]

Private Sub DataGridView1_CellFormatting(ByVal sender As Object, _ByVal e As DataGridViewCellFormattingEventArgs) _Handles DataGridView1.CellFormattingDim dgv As DataGridView = CType(sender, DataGridView)If dgv.Columns(e.ColumnIndex).Name = "Column1" AndAlso _TypeOf e.Value Is String ThenDim str As String = e.Value.ToString()e.Value = str.ToUpper()e.FormattingApplied = TrueEnd If
End Sub

[C#]

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]

Private Sub DataGridView1_CellErrorTextNeeded(ByVal sender As Object, _ByVal e As DataGridViewCellErrorTextNeededEventArgs) _Handles DataGridView1.CellErrorTextNeededDim dgv As DataGridView = CType(sender, DataGridView)Dim cellVal As Object = dgv(e.ColumnIndex, e.RowIndex).ValueIf TypeOf cellVal Is Integer AndAlso CInt(cellVal) < 0 Thene.ErrorText = "不能输入负整数。"End If
End Sub
Private Sub DataGridView1_RowErrorTextNeeded(ByVal sender As Object, _ByVal e As DataGridViewRowErrorTextNeededEventArgs) _Handles DataGridView1.RowErrorTextNeededDim dgv As DataGridView = CType(sender, DataGridView)If dgv("Column1", e.RowIndex).Value Is DBNull.Value AndAlso _dgv("Column2", e.RowIndex).Value Is DBNull.Value Thene.ErrorText = _"请至少在Column1和Column2中输入值。"End If
End Sub

[C#]

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]

'CellValidating活动处理程序
Private Sub DataGridView1_CellValidating(ByVal sender As Object, _ByVal e As DataGridViewCellValidatingEventArgs) _Handles DataGridView1.CellValidatingDim 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 = TrueEnd If
End Sub
'CellValidated事件处理程序
Private Sub DataGridView1_CellValidated(ByVal sender As Object, _ByVal e As DataGridViewCellEventArgs) _Handles DataGridView1.CellValidatedDim dgv As DataGridView = CType(sender, DataGridView)'消除错误文本dgv.Rows(e.RowIndex).ErrorText = Nothing
End Sub

[C#]

//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]

Private Sub DataGridView1_DataError(ByVal sender As Object, _ByVal e As DataGridViewDataErrorEventArgs) _Handles DataGridView1.DataErrorIf Not (e.Exception Is Nothing) ThenMessageBox.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#]

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]

Private Sub DataGridView1_DataError(ByVal sender As Object, _ByVal e As DataGridViewDataErrorEventArgs) _Handles DataGridView1.DataErrore.Cancel = False
End Sub

[C#]

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]

Private Sub Form1_Load(ByVal sender As System.Object, _ByVal e As System.EventArgs) Handles MyBase.LoadDim c As DataGridViewColumnFor Each c In DataGridView1.Columnsc.SortMode = DataGridViewColumnSortMode.AutomaticNext c
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, _ByVal e As System.EventArgs) Handles Button1.ClickIf DataGridView1.CurrentCell Is Nothing ThenReturnEnd IfDim sortColumn As DataGridViewColumn = _DataGridView1.CurrentCell.OwningColumnDim sortDirection As System.ComponentModel.ListSortDirection = _System.ComponentModel.ListSortDirection.AscendingIf Not (DataGridView1.SortedColumn Is Nothing) AndAlso _DataGridView1.SortedColumn.Equals(sortColumn) ThensortDirection = IIf(DataGridView1.SortOrder = SortOrder.Ascending, _System.ComponentModel.ListSortDirection.Descending, _System.ComponentModel.ListSortDirection.Ascending)End IfDataGridView1.Sort(sortColumn, sortDirection)
End Sub

[C#]

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]

Private Sub DataGridView1_ColumnHeaderMouseClick(ByVal sender As Object, _ByVal e As DataGridViewCellMouseEventArgs) _Handles DataGridView1.ColumnHeaderMouseClickDim clickedColumn As DataGridViewColumn = _DataGridView1.Columns(e.ColumnIndex)If clickedColumn.SortMode <> DataGridViewColumnSortMode.Automatic ThenMe.SortRows(clickedColumn, True)End If
End Sub
Private Sub DataGridView1_RowsAdded(ByVal sender As Object, _ByVal e As DataGridViewRowsAddedEventArgs) _Handles DataGridView1.RowsAddedMe.SortRows(DataGridView1.SortedColumn, False)
End Sub
Private Sub DataGridView1_CellValueChanged(ByVal sender As Object, _ByVal e As DataGridViewCellEventArgs) _Handles DataGridView1.CellValueChangedIf Not (DataGridView1.SortedColumn Is Nothing) AndAlso _e.ColumnIndex = DataGridView1.SortedColumn.Index ThenMe.SortRows(DataGridView1.SortedColumn, False)End If
End Sub
Private Sub SortRows(ByVal sortColumn As DataGridViewColumn, _ByVal orderToggle As Boolean)If sortColumn Is Nothing ThenReturnEnd IfIf sortColumn.SortMode = DataGridViewColumnSortMode.Programmatic AndAlso _Not (DataGridView1.SortedColumn Is Nothing) AndAlso _Not DataGridView1.SortedColumn.Equals(sortColumn) ThenDataGridView1.SortedColumn.HeaderCell.SortGlyphDirection = _SortOrder.NoneEnd IfDim sortDirection As System.ComponentModel.ListSortDirectionIf orderToggle ThensortDirection = IIf(DataGridView1.SortOrder = SortOrder.Descending, _System.ComponentModel.ListSortDirection.Ascending, _System.ComponentModel.ListSortDirection.Descending)ElsesortDirection = IIf(DataGridView1.SortOrder = SortOrder.Descending, _System.ComponentModel.ListSortDirection.Descending, _System.ComponentModel.ListSortDirection.Ascending)End IfDim sOrder As SortOrder = _IIf(sortDirection = System.ComponentModel.ListSortDirection.Ascending, _SortOrder.Ascending, SortOrder.Descending)DataGridView1.Sort(sortColumn, sortDirection)If sortColumn.SortMode = DataGridViewColumnSortMode.Programmatic ThensortColumn.HeaderCell.SortGlyphDirection = sOrderEnd If
End Sub

[C#]

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]

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#]

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]

Dim cellStyle As New DataGridViewCellStyle()
cellStyle.BackColor = Color.Yellow
For i As Integer = 0 To DataGridView1.Columns.Count - 1If i Mod 2 = 0 ThenDataGridView1.Columns(i).DefaultCellStyle = cellStyleEnd If
Next i
For i As Integer = 0 To DataGridView1.Columns.Count - 1If i Mod 2 = 0 ThenDataGridView1.Columns(i).DefaultCellStyle.BackColor = Color.YellowEnd If
Next i

[C#]

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]

Private Sub DataGridView1_CellMouseEnter(ByVal sender As Object, _ByVal e As DataGridViewCellEventArgs) _Handles DataGridView1.CellMouseEnterIf e.ColumnIndex >= 0 And e.RowIndex >= 0 ThenDim dgv As DataGridView = CType(sender, DataGridView)dgv(e.ColumnIndex, e.RowIndex).Style.BackColor = Color.Reddgv(e.ColumnIndex, e.RowIndex).Style.SelectionBackColor = Color.RedEnd If
End Sub
Private Sub DataGridView1_CellMouseLeave(ByVal sender As Object, _ByVal e As DataGridViewCellEventArgs) _Handles DataGridView1.CellMouseLeaveIf e.ColumnIndex >= 0 And e.RowIndex >= 0 ThenDim dgv As DataGridView = CType(sender, DataGridView)dgv(e.ColumnIndex, e.RowIndex).Style.BackColor = Color.Empty
dgv(e.ColumnIndex, e.RowIndex).Style.SelectionBackColor = Color.EmptyEnd If
End Sub

[C#]

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]

Private defaultCellStyle As DataGridViewCellStyle
Private mouseCellStyle As DataGridViewCellStyle
Private Sub Form1_Load(ByVal sender As System.Object, _ByVal e As System.EventArgs) Handles MyBase.LoadMe.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.CellMouseEnterIf e.ColumnIndex >= 0 And e.RowIndex >= 0 ThenDim dgv As DataGridView = CType(sender, DataGridView)dgv(e.ColumnIndex, e.RowIndex).Style = Me.mouseCellStyleEnd If
End Sub
Private Sub DataGridView1_CellMouseLeave(ByVal sender As Object, _ByVal e As DataGridViewCellEventArgs) _Handles DataGridView1.CellMouseLeaveIf e.ColumnIndex >= 0 And e.RowIndex >= 0 ThenDim dgv As DataGridView = CType(sender, DataGridView)dgv(e.ColumnIndex, e.RowIndex).Style = Me.defaultCellStyleEnd If
End Sub

[C#]

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]

Private Sub DataGridView1_CellFormatting(ByVal sender As Object, _ByVal e As DataGridViewCellFormattingEventArgs) _Handles DataGridView1.CellFormattingDim dgv As DataGridView = CType(sender, DataGridView)If dgv.Columns(e.ColumnIndex).Name = "Column1" AndAlso _TypeOf e.Value Is Integer ThenDim val As Integer = CInt(e.Value)If val < 0 Thene.CellStyle.BackColor = Color.YellowElse If val = 0 Thene.CellStyle.BackColor = Color.RedEnd IfEnd If
End Sub

[C#]

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]

Private Sub DataGridView1_CellPainting(ByVal sender As Object, _ByVal e As DataGridViewCellPaintingEventArgs) _Handles DataGridView1.CellPaintingIf e.ColumnIndex >= 0 AndAlso e.RowIndex >= 0 AndAlso _(e.PaintParts And DataGridViewPaintParts.Background) = _DataGridViewPaintParts.Background ThenDim bColor1, bColor2 As ColorIf (e.PaintParts And DataGridViewPaintParts.SelectionBackground) = _DataGridViewPaintParts.SelectionBackground AndAlso _(e.State And DataGridViewElementStates.Selected) = _DataGridViewElementStates.Selected ThenbColor1 = e.CellStyle.SelectionBackColorbColor2 = Color.BlackElsebColor1 = e.CellStyle.BackColorbColor2 = Color.LemonChiffonEnd IfDim b As New System.Drawing.Drawing2D.LinearGradientBrush( _e.CellBounds, bColor1, bColor2, _System.Drawing.Drawing2D.LinearGradientMode.Horizontal)Trye.Graphics.FillRectangle(b, e.CellBounds)Finallyb.Dispose()End TryDim paintParts As DataGridViewPaintParts = _e.PaintParts And Not DataGridViewPaintParts.Backgrounde.Paint(e.ClipBounds, paintParts)e.Handled = TrueEnd If
End Sub

[C#]

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]

Private cellBackImage As New Bitmap("C:/back.gif")
Private Sub DataGridView1_CellPainting(ByVal sender As Object, _ByVal e As DataGridViewCellPaintingEventArgs) _Handles DataGridView1.CellPaintingIf e.ColumnIndex >= 0 AndAlso e.RowIndex >= 0 AndAlso _(e.PaintParts And DataGridViewPaintParts.Background) = _DataGridViewPaintParts.Background ThenDim 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) / 2Dim y As Integer = e.CellBounds.Y + _(e.CellBounds.Height - cellBackImage.Height) / 2e.Graphics.DrawImage(cellBackImage, x, y)Dim paintParts As DataGridViewPaintParts = _e.PaintParts And Not backPartse.Paint(e.ClipBounds, paintParts)e.Handled = TrueEnd If
End Sub

[C#]

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]

Private Sub DataGridView1_RowPostPaint(ByVal sender As Object, _ByVal e As DataGridViewRowPostPaintEventArgs) _Handles DataGridView1.RowPostPaintDim dgv As DataGridView = CType(sender, DataGridView)Dim linePen As PenSelect Case e.RowIndex Mod 3Case 0linePen = Pens.BlueCase 1linePen = Pens.GreenCase ElselinePen = Pens.RedEnd SelectDim startX As Integer = IIf(dgv.RowHeadersVisible, dgv.RowHeadersWidth, 0)Dim startY As Integer = e.RowBounds.Top + e.RowBounds.Height - 1Dim endX As Integer = startX + _dgv.Columns.GetColumnsWidth(DataGridViewElementStates.Visible) - _dgv.HorizontalScrollingOffsete.Graphics.DrawLine(linePen, startX, startY, endX, startY)
End Sub

[C#]

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]

Private Sub DataGridView1_RowPrePaint(ByVal sender As Object, _ByVal e As DataGridViewRowPrePaintEventArgs) _Handles DataGridView1.RowPrePaintIf (e.PaintParts And DataGridViewPaintParts.Background) = _DataGridViewPaintParts.Background ThenDim bColor1, bColor2 As ColorIf (e.PaintParts And DataGridViewPaintParts.SelectionBackground) = _DataGridViewPaintParts.SelectionBackground AndAlso _(e.State And DataGridViewElementStates.Selected) = _DataGridViewElementStates.Selected ThenbColor1 = e.InheritedRowStyle.SelectionBackColorbColor2 = Color.BlackElsebColor1 = e.InheritedRowStyle.BackColorbColor2 = Color.YellowGreenEnd IfDim dgv As DataGridView = CType(sender, DataGridView)Dim rectLeft2 As Integer = _IIf(dgv.RowHeadersVisible, dgv.RowHeadersWidth, 0)Dim rectLeft As Integer = _rectLeft2 - dgv.HorizontalScrollingOffsetDim 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 = rectLeft2rect.Width -= dgv.HorizontalScrollingOffsete.Graphics.FillRectangle(b, rect)End Usinge.PaintHeader(True)e.PaintParts = _e.PaintParts And Not DataGridViewPaintParts.BackgroundEnd If
End Sub
Private Sub DataGridView1_ColumnWidthChanged(ByVal sender As Object, _ByVal e As DataGridViewColumnEventArgs) _Handles DataGridView1.ColumnWidthChangedDim dgv As DataGridView = CType(sender, DataGridView)dgv.Invalidate()
End Sub

[C#]

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]

Private Sub DataGridView1_CellPainting(ByVal sender As Object, _ByVal e As DataGridViewCellPaintingEventArgs) _Handles DataGridView1.CellPaintingIf e.ColumnIndex < 0 And e.RowIndex >= 0 Thene.Paint(e.ClipBounds, DataGridViewPaintParts.All)Dim indexRect As Rectangle = e.CellBoundsindexRect.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 = TrueEnd If
End Sub

[C#]

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]

Private Sub DataGridView1_RowPostPaint(ByVal sender As Object, _ByVal e As DataGridViewRowPostPaintEventArgs) _Handles DataGridView1.RowPostPaintDim dgv As DataGridView = CType(sender, DataGridView)If dgv.RowHeadersVisible ThenDim 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#]

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]

Private Sub DataGridView1_CellPainting(ByVal sender As Object, _ByVal e As DataGridViewCellPaintingEventArgs) _Handles DataGridView1.CellPaintingIf e.ColumnIndex >= 0 And e.RowIndex >= 0 ThenDim paintParts As DataGridViewPaintParts = _e.PaintParts And Not DataGridViewPaintParts.Focuse.Paint(e.ClipBounds, paintParts)e.Handled = TrueEnd If
End Sub

[C#]

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]

Private Sub DataGridView1_RowPrePaint(ByVal sender As Object, _ByVal e As DataGridViewRowPrePaintEventArgs) _Handles DataGridView1.RowPrePainte.PaintParts = e.PaintParts And Not DataGridViewPaintParts.Focus
End Sub

[C#]

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]

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#]

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]

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#]

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]

Private Sub DataGridView1_CellEnter(ByVal sender As Object, _ByVal e As DataGridViewCellEventArgs) _Handles DataGridView1.CellEnterDim dgv As DataGridView = CType(sender, DataGridView)If dgv.Columns(e.ColumnIndex).Name = "ComboBox" AndAlso _TypeOf dgv.Columns(e.ColumnIndex) Is DataGridViewComboBoxColumn ThenSendKeys.Send("{F4}")End If
End Sub

[C#]

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]

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

[C#]

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

按钮按下事件取得

[VB.NET]

Private Sub DataGridView1_CellContentClick(ByVal sender As Object, _ByVal e As DataGridViewCellEventArgs) _Handles DataGridView1.CellContentClickDim dgv As DataGridView = CType(sender, DataGridView)If dgv.Columns(e.ColumnIndex).Name = "Button" ThenMessageBox.Show((e.RowIndex.ToString() + _"行按钮被点击了。"))End If
End Sub

[C#]

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]

Private Sub DataGridView1_CellContentClick(ByVal sender As Object, _ByVal e As DataGridViewCellEventArgs) _Handles DataGridView1.CellContentClickDim dgv As DataGridView = CType(sender, DataGridView)If dgv.Columns(e.ColumnIndex).Name = "Link" ThenMessageBox.Show((e.RowIndex.ToString() + _"行按钮被点击了。"))Dim cell As DataGridViewLinkCell = _CType(dgv(e.ColumnIndex, e.RowIndex), DataGridViewLinkCell)cell.LinkVisited = TrueEnd If
End Sub

[C#]

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]

Private Sub DataGridView1_EditingControlShowing(ByVal sender As Object, _ByVal e As DataGridViewEditingControlShowingEventArgs) _Handles DataGridView1.EditingControlShowingIf TypeOf e.Control Is DataGridViewTextBoxEditingControl ThenDim dgv As DataGridView = CType(sender, DataGridView)Dim tb As DataGridViewTextBoxEditingControl = _CType(e.Control, DataGridViewTextBoxEditingControl)If dgv.CurrentCell.OwningColumn.Name = "Column1" Thentb.ImeMode = Windows.Forms.ImeMode.DisableElsetb.ImeMode = dgv.ImeModeEnd IfEnd If
End Sub

[C#]

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;elsetb.ImeMode = dgv.ImeMode;}
}

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

52. DataGridView输入自动完成

[VB.NET]

Dim autoCompleteSource As New AutoCompleteStringCollection()
Private Sub DataGridView1_EditingControlShowing( _ByVal sender As Object, _ByVal e As DataGridViewEditingControlShowingEventArgs) _Handles DataGridView1.EditingControlShowingDim dgv As DataGridView = CType(sender, DataGridView)If TypeOf e.Control Is TextBox ThenDim tb As TextBox = CType(e.Control, TextBox)If dgv.CurrentCell.OwningColumn.Name = "Column1" Thentb.AutoCompleteMode = AutoCompleteMode.SuggestAppendtb.AutoCompleteSource = _Windows.Forms.AutoCompleteSource.CustomSourcetb.AutoCompleteCustomSource = Me.autoCompleteSourceElsetb.AutoCompleteMode = AutoCompleteMode.NoneEnd IfEnd If
End Sub
Private Sub DataGridView1_DataSourceChanged( _ByVal sender As Object, ByVal e As EventArgs) _Handles DataGridView1.DataSourceChangedDim dgv As DataGridView = CType(sender, DataGridView)Me.autoCompleteSource.Clear()Dim r As DataGridViewRowFor Each r In dgv.RowsDim val As String = r.Cells("Column1").ValueIf Not String.IsNullOrEmpty(val) AndAlso _Not Me.autoCompleteSource.Contains(val) ThenautoCompleteSource.Add(val)End IfNext r
End Sub
Private Sub DataGridView1_CellValueChanged(ByVal sender As Object, _ByVal e As DataGridViewCellEventArgs) _Handles DataGridView1.CellValueChangedDim dgv As DataGridView = CType(sender, DataGridView)If dgv.Columns(e.ColumnIndex).Name = "Column1" ThenDim val As String = dgv(e.ColumnIndex, e.RowIndex).ValueIf Not String.IsNullOrEmpty(val) AndAlso _Not Me.autoCompleteSource.Contains(val) ThenautoCompleteSource.Add(val)End IfEnd If
End Sub

[C#]

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]

Private Sub DataGridView1_EditingControlShowing(ByVal sender As Object, _ByVal e As DataGridViewEditingControlShowingEventArgs) _Handles DataGridView1.EditingControlShowingIf TypeOf e.Control Is DataGridViewTextBoxEditingControl ThenDim dgv As DataGridView = CType(sender, DataGridView)Dim tb As DataGridViewTextBoxEditingControl = _CType(e.Control, DataGridViewTextBoxEditingControl)RemoveHandler tb.KeyPress, AddressOf dataGridViewTextBox_KeyPressIf dgv.CurrentCell.OwningColumn.Name = "Column1" Then
AddHandler tb.KeyPress, AddressOf dataGridViewTextBox_KeyPressEnd IfEnd If
End Sub
Private Sub dataGridViewTextBox_KeyPress(ByVal sender As Object, _ByVal e As KeyPressEventArgs) _Handles DataGridView1.KeyPressIf e.KeyChar < "0"c Or e.KeyChar > "9"c Thene.Handled = TrueEnd If
End Sub​​​​​​​

[C#]

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]

Private dataGridViewComboBox As DataGridViewComboBoxEditingControl = Nothing
Private Sub DataGridView1_EditingControlShowing(ByVal sender As Object, _ByVal e As DataGridViewEditingControlShowingEventArgs) _Handles DataGridView1.EditingControlShowingIf TypeOf e.Control Is DataGridViewComboBoxEditingControl ThenDim dgv As DataGridView = CType(sender, DataGridView)If dgv.CurrentCell.OwningColumn.Name = "ComboBox" ThenMe.dataGridViewComboBox = _CType(e.Control, DataGridViewComboBoxEditingControl)AddHandler Me.dataGridViewComboBox.SelectedIndexChanged, _AddressOf dataGridViewComboBox_SelectedIndexChangedEnd IfEnd If
End Sub
Private Sub DataGridView1_CellEndEdit(ByVal sender As Object, _ByVal e As DataGridViewCellEventArgs) _Handles DataGridView1.CellEndEditIf Not (Me.dataGridViewComboBox Is Nothing) ThenRemoveHandler Me.dataGridViewComboBox.SelectedIndexChanged, _AddressOf dataGridViewComboBox_SelectedIndexChangedMe.dataGridViewComboBox = NothingEnd 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#]

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]

Private Sub DataGridView1_EditingControlShowing(ByVal sender As Object, _ByVal e As DataGridViewEditingControlShowingEventArgs) _Handles DataGridView1.EditingControlShowingIf TypeOf e.Control Is DataGridViewComboBoxEditingControl ThenDim dgv As DataGridView = CType(sender, DataGridView)If dgv.CurrentCell.OwningColumn.Name = "ComboBox" ThenDim cb As DataGridViewComboBoxEditingControl = _CType(e.Control, DataGridViewComboBoxEditingControl)cb.DropDownStyle = ComboBoxStyle.DropDownEnd IfEnd If
End Sub
Private Sub DataGridView1_CellValidating(ByVal sender As Object, _ByVal e As DataGridViewCellValidatingEventArgs) _Handles DataGridView1.CellValidatingDim dgv As DataGridView = CType(sender, DataGridView)If dgv.Columns(e.ColumnIndex).Name = "ComboBox" AndAlso _TypeOf dgv.Columns(e.ColumnIndex) Is DataGridViewComboBoxColumn ThenDim cbc As DataGridViewComboBoxColumn = _CType(dgv.Columns(e.ColumnIndex), DataGridViewComboBoxColumn)If Not cbc.Items.Contains(e.FormattedValue) Thencbc.Items.Add(e.FormattedValue)End IfEnd If
End Sub

[C#]

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]

Imports System
Imports System.Drawing
Imports System.Windows.FormsPublic Class DataGridViewProgressBarColumnInherits DataGridViewTextBoxColumnPublic Sub New()Me.CellTemplate = New DataGridViewProgressBarCell()End SubPublic Overrides Property CellTemplate() As DataGridViewCellGetReturn MyBase.CellTemplateEnd GetSet(ByVal value As DataGridViewCell)If Not TypeOf value Is DataGridViewProgressBarCell ThenThrow New InvalidCastException( _"DataGridViewProgressBarCellオブジェクトを" + _"指定してください。")End IfMyBase.CellTemplate = valueEnd SetEnd PropertyPublic Property Maximum() As IntegerGetReturn CType(Me.CellTemplate, DataGridViewProgressBarCell).MaximumEnd GetSet(ByVal value As Integer)If Me.Maximum = value ThenReturnEnd If
CType(Me.CellTemplate, DataGridViewProgressBarCell).Maximum = valueIf Me.DataGridView Is Nothing ThenReturnEnd IfDim rowCount As Integer = Me.DataGridView.RowCountDim i As IntegerFor i = 0 To rowCount - 1Dim r As DataGridViewRow = Me.DataGridView.Rows.SharedRow(i)CType(r.Cells(Me.Index), DataGridViewProgressBarCell).Maximum = _valueNext iEnd SetEnd PropertyPublic Property Mimimum() As IntegerGetReturn CType(Me.CellTemplate, DataGridViewProgressBarCell).MimimumEnd GetSet(ByVal value As Integer)If Me.Mimimum = value ThenReturnEnd IfCType(Me.CellTemplate, DataGridViewProgressBarCell).Mimimum = valueIf Me.DataGridView Is Nothing ThenReturnEnd IfDim rowCount As Integer = Me.DataGridView.RowCountDim i As IntegerFor i = 0 To rowCount - 1Dim r As DataGridViewRow = Me.DataGridView.Rows.SharedRow(i)CType(r.Cells(Me.Index), DataGridViewProgressBarCell).Mimimum = _valueNext iEnd SetEnd Property
End ClassPublic Class DataGridViewProgressBarCellInherits DataGridViewTextBoxCellPublic Sub New()Me.maximumValue = 100Me.mimimumValue = 0End SubPrivate maximumValue As IntegerPublic Property Maximum() As IntegerGetReturn Me.maximumValueEnd GetSet(ByVal value As Integer)Me.maximumValue = valueEnd SetEnd PropertyPrivate mimimumValue As IntegerPublic Property Mimimum() As IntegerGetReturn Me.mimimumValueEnd GetSet(ByVal value As Integer)Me.mimimumValue = valueEnd SetEnd PropertyPublic Overrides ReadOnly Property ValueType() As TypeGetReturn GetType(Integer)End GetEnd PropertyPublic Overrides ReadOnly Property DefaultNewRowValue() As ObjectGetReturn 0End GetEnd PropertyPublic Overrides Function Clone() As ObjectDim cell As DataGridViewProgressBarCell = _CType(MyBase.Clone(), DataGridViewProgressBarCell)cell.Maximum = Me.Maximumcell.Mimimum = Me.MimimumReturn cellEnd FunctionProtected 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 = 0If TypeOf value Is Integer ThenintValue = CInt(value)End IfIf intValue < Me.mimimumValue ThenintValue = Me.mimimumValueEnd IfIf intValue > Me.maximumValue ThenintValue = Me.maximumValueEnd IfDim rate As Double = CDbl(intValue - Me.mimimumValue) / _(Me.maximumValue - Me.mimimumValue)If (paintParts And DataGridViewPaintParts.Border) = _DataGridViewPaintParts.Border ThenMe.PaintBorder(graphics, clipBounds, cellBounds, _cellStyle, advancedBorderStyle)End IfDim 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 ColorIf isSelected AndAlso _(paintParts And DataGridViewPaintParts.SelectionBackground) = _DataGridViewPaintParts.SelectionBackground ThenbkColor = cellStyle.SelectionBackColorElsebkColor = cellStyle.BackColorEnd IfIf (paintParts And DataGridViewPaintParts.Background) = _DataGridViewPaintParts.Background ThenDim backBrush As New SolidBrush(bkColor)Trygraphics.FillRectangle(backBrush, paintRect)FinallybackBrush.Dispose()End TryEnd IfpaintRect.Offset(cellStyle.Padding.Right, cellStyle.Padding.Top)paintRect.Width -= cellStyle.Padding.HorizontalpaintRect.Height -= cellStyle.Padding.VerticalIf (paintParts And DataGridViewPaintParts.ContentForeground) = _DataGridViewPaintParts.ContentForeground ThenIf ProgressBarRenderer.IsSupported ThenProgressBarRenderer.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)Elsegraphics.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 IfEnd IfIf Me.DataGridView.CurrentCellAddress.X = Me.ColumnIndex AndAlso _Me.DataGridView.CurrentCellAddress.Y = Me.RowIndex AndAlso _(paintParts And DataGridViewPaintParts.Focus) = _DataGridViewPaintParts.Focus AndAlso _Me.DataGridView.Focused ThenDim focusRect As Rectangle = paintRectfocusRect.Inflate(-3, -3)ControlPaint.DrawFocusRectangle(graphics, focusRect)End IfIf (paintParts And DataGridViewPaintParts.ContentForeground) = _DataGridViewPaintParts.ContentForeground ThenDim txt As String = String.Format("{0}%", Math.Round((rate * 100)))Dim flags As TextFormatFlags = _TextFormatFlags.HorizontalCenter Or _TextFormatFlags.VerticalCenterDim fColor As Color = cellStyle.ForeColorpaintRect.Inflate(-2, -2)TextRenderer.DrawText( _graphics, txt, cellStyle.Font, paintRect, fColor, flags)End IfIf (paintParts And DataGridViewPaintParts.ErrorIcon) = _DataGridViewPaintParts.ErrorIcon AndAlso _Me.DataGridView.ShowCellErrors AndAlso _Not String.IsNullOrEmpty(errorText) ThenDim iconBounds As Rectangle = _Me.GetErrorIconBounds(graphics, cellStyle, rowIndex)iconBounds.Offset(cellBounds.X, cellBounds.Y)Me.PaintErrorIcon(graphics, iconBounds, cellBounds, errorText)End IfEnd Sub
End Class

[C#]

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]

Imports System
Imports System.Windows.Forms
Public Class DataGridViewMaskedTextBoxColumnInherits DataGridViewColumnPublic Sub New()MyBase.New(New DataGridViewMaskedTextBoxCell())End SubPrivate maskValue As String = ""Public Property Mask() As StringGetReturn Me.maskValueEnd GetSet(ByVal value As String)Me.maskValue = valueEnd SetEnd PropertyPublic Overrides Function Clone() As ObjectDim col As DataGridViewMaskedTextBoxColumn = _CType(MyBase.Clone(), DataGridViewMaskedTextBoxColumn)col.Mask = Me.MaskReturn colEnd FunctionPublic Overrides Property CellTemplate() As DataGridViewCellGetReturn MyBase.CellTemplateEnd GetSet(ByVal value As DataGridViewCell)If Not TypeOf value Is DataGridViewMaskedTextBoxCell ThenThrow New InvalidCastException( _"DataGridViewMaskedTextBoxCellオブジェクトを" + _"指定してください。")End IfMyBase.CellTemplate = valueEnd SetEnd Property
End Class
Public Class DataGridViewMaskedTextBoxCellInherits DataGridViewTextBoxCellPublic Sub New()End SubPublic 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.EditingControlIf Not (maskedBox Is Nothing) ThenmaskedBox.Text = IIf(Me.Value Is Nothing, "", Me.Value.ToString())Dim column As DataGridViewMaskedTextBoxColumn = Me.OwningColumnIf Not (column Is Nothing) ThenmaskedBox.Mask = column.MaskEnd IfEnd IfEnd SubPublic Overrides ReadOnly Property EditType() As TypeGetReturn GetType(DataGridViewMaskedTextBoxEditingControl)End GetEnd PropertyPublic Overrides ReadOnly Property ValueType() As TypeGetReturn GetType(Object)End GetEnd PropertyPublic Overrides ReadOnly Property DefaultNewRowValue() As ObjectGetReturn MyBase.DefaultNewRowValueEnd GetEnd Property
End Class
Public Class DataGridViewMaskedTextBoxEditingControlInherits MaskedTextBoxImplements IDataGridViewEditingControlPrivate dataGridView As DataGridViewPrivate rowIndex As IntegerPrivate valueChanged As BooleanPublic Sub New()Me.TabStop = FalseEnd SubPublic Function GetEditingControlFormattedValue( _ByVal context As DataGridViewDataErrorContexts) As Object _Implements IDataGridViewEditingControl.GetEditingControlFormattedValueReturn Me.TextEnd FunctionPublic Property EditingControlFormattedValue() As Object _Implements IDataGridViewEditingControl.EditingControlFormattedValueGetReturn Me.GetEditingControlFormattedValue( _DataGridViewDataErrorContexts.Formatting)End GetSet(ByVal value As Object)Me.Text = CStr(value)End SetEnd PropertyPublic Sub ApplyCellStyleToEditingControl( _ByVal dataGridViewCellStyle As DataGridViewCellStyle) _Implements IDataGridViewEditingControl.ApplyCellStyleToEditingControlMe.Font = dataGridViewCellStyle.FontMe.ForeColor = dataGridViewCellStyle.ForeColorMe.BackColor = dataGridViewCellStyle.BackColorSelect Case dataGridViewCellStyle.AlignmentCase DataGridViewContentAlignment.BottomCenter, _DataGridViewContentAlignment.MiddleCenter, _DataGridViewContentAlignment.TopCenterMe.TextAlign = HorizontalAlignment.CenterCase DataGridViewContentAlignment.BottomRight, _DataGridViewContentAlignment.MiddleRight, _DataGridViewContentAlignment.TopRightMe.TextAlign = HorizontalAlignment.RightCase ElseMe.TextAlign = HorizontalAlignment.LeftEnd SelectEnd SubPublic Property EditingControlDataGridView() As DataGridView _Implements IDataGridViewEditingControl.EditingControlDataGridViewGetReturn Me.dataGridViewEnd GetSet(ByVal value As DataGridView)Me.dataGridView = valueEnd SetEnd PropertyPublic Property EditingControlRowIndex() As Integer _Implements IDataGridViewEditingControl.EditingControlRowIndexGetReturn Me.rowIndexEnd GetSet(ByVal value As Integer)Me.rowIndex = valueEnd SetEnd PropertyPublic Property EditingControlValueChanged() As Boolean _Implements IDataGridViewEditingControl.EditingControlValueChangedGetReturn Me.valueChangedEnd GetSet(ByVal value As Boolean)Me.valueChanged = valueEnd SetEnd PropertyPublic Function EditingControlWantsInputKey(ByVal keyData As Keys, _ByVal dataGridViewWantsInputKey As Boolean) As Boolean _Implements IDataGridViewEditingControl.EditingControlWantsInputKeySelect Case keyData And Keys.KeyCodeCase Keys.Right, Keys.End, Keys.Left, Keys.HomeReturn TrueCase ElseReturn FalseEnd SelectEnd FunctionPublic ReadOnly Property EditingPanelCursor() As Cursor _Implements IDataGridViewEditingControl.EditingPanelCursorGetReturn MyBase.CursorEnd GetEnd PropertyPublic Sub PrepareEditingControlForEdit(ByVal selectAll As Boolean) _Implements IDataGridViewEditingControl.PrepareEditingControlForEditIf selectAll ThenMe.SelectAll()ElseMe.SelectionStart = Me.TextLengthEnd IfEnd SubPublic ReadOnly Property RepositionEditingControlOnValueChange() _As Boolean _Implements _IDataGridViewEditingControl.RepositionEditingControlOnValueChangeGetReturn FalseEnd GetEnd PropertyProtected Overrides Sub OnTextChanged(ByVal e As EventArgs)MyBase.OnTextChanged(e)Me.valueChanged = TrueMe.dataGridView.NotifyCurrentCellDirty(True)End Sub
End Class

[C#]

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 asDataGridViewMaskedTextBoxEditingControl;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;}}#endregionprotected 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]

Public Class DataGridViewErrorIconColumnInherits DataGridViewImageColumnPublic Sub New()Me.CellTemplate = New DataGridViewErrorIconCell()Me.ValueType = Me.CellTemplate.ValueTypeEnd Sub
End ClassPublic Class DataGridViewErrorIconCellInherits DataGridViewImageCellPublic Sub New()Me.ValueType = GetType(Integer)End SubProtected 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 ObjectSelect Case CInt(value)Case 1Return SystemIcons.InformationCase 2Return SystemIcons.WarningCase 3Return SystemIcons.ErrorCase ElseReturn NothingEnd SelectEnd FunctionPublic Overrides ReadOnly Property DefaultNewRowValue() As ObjectGetReturn 0End GetEnd Property
End Class

[C#]

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

这篇关于DataGridView用法合集【精品】的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1136207

相关文章

【专题】2024飞行汽车技术全景报告合集PDF分享(附原数据表)

原文链接: https://tecdat.cn/?p=37628 6月16日,小鹏汇天旅航者X2在北京大兴国际机场临空经济区完成首飞,这也是小鹏汇天的产品在京津冀地区进行的首次飞行。小鹏汇天方面还表示,公司准备量产,并计划今年四季度开启预售小鹏汇天分体式飞行汽车,探索分体式飞行汽车城际通勤。阅读原文,获取专题报告合集全文,解锁文末271份飞行汽车相关行业研究报告。 据悉,业内人士对飞行汽车行业

bytes.split的用法和注意事项

当然,我很乐意详细介绍 bytes.Split 的用法和注意事项。这个函数是 Go 标准库中 bytes 包的一个重要组成部分,用于分割字节切片。 基本用法 bytes.Split 的函数签名如下: func Split(s, sep []byte) [][]byte s 是要分割的字节切片sep 是用作分隔符的字节切片返回值是一个二维字节切片,包含分割后的结果 基本使用示例: pa

EasyPlayer.js网页H5 Web js播放器能力合集

最近遇到一个需求,要求做一款播放器,发现能力上跟EasyPlayer.js基本一致,满足要求: 需求 功性能 分类 需求描述 功能 预览 分屏模式 单分屏(单屏/全屏) 多分屏(2*2) 多分屏(3*3) 多分屏(4*4) 播放控制 播放(单个或全部) 暂停(暂停时展示最后一帧画面) 停止(单个或全部) 声音控制(开关/音量调节) 主辅码流切换 辅助功能 屏

UVM:callback机制的意义和用法

1. 作用         Callback机制在UVM验证平台,最大用处就是为了提高验证平台的可重用性。在不创建复杂的OOP层次结构前提下,针对组件中的某些行为,在其之前后之后,内置一些函数,增加或者修改UVM组件的操作,增加新的功能,从而实现一个环境多个用例。此外还可以通过Callback机制构建异常的测试用例。 2. 使用步骤         (1)在UVM组件中内嵌callback函

C++语法知识点合集:11.模板

文章目录 一、非类型模板参数1.非类型模板参数的基本形式2.指针作为非类型模板参数3.引用作为非类型模板参数4.非类型模板参数的限制和陷阱:5.几个问题 二、模板的特化1.概念2.函数模板特化3.类模板特化(1)全特化(2)偏特化(3)类模板特化应用示例 三、模板分离编译1.概念2.模板的分离编译 模版总结 一、非类型模板参数 模板参数分类类型形参与非类型形参 非类型模板

这些ES6用法你都会吗?

一 关于取值 取值在程序中非常常见,比如从对象obj中取值 const obj = {a:1b:2c:3d:4} 吐槽: const a = obj.a;const b = obj.b;const c = obj.c;//或者const f = obj.a + obj.b;const g = obj.c + obj.d; 改进:用ES6解构赋值

2021-8-14 react笔记-2 创建组件 基本用法

1、目录解析 public中的index.html为入口文件 src目录中文件很乱,先整理文件夹。 新建components 放组件 新建assets放资源   ->/images      ->/css 把乱的文件放进去  修改App.js 根组件和index.js入口文件中的引入路径 2、新建组件 在components文件夹中新建[Name].js文件 //组件名首字母大写

Linux性能分析工具合集

Linux性能分析工具合集 工具合集主要包含以下各种工具,对于了解Linux系统结构、网络结构、内核层次具有一定的帮助。 Linux Performance Observability ToolsLinux Static Performance ToolsLinux Performance Benchmark ToolsLinux Performance Tuning ToolsLinux

Cmake之3.0版本重要特性及用法实例(十三)

简介: CSDN博客专家、《Android系统多媒体进阶实战》一书作者 新书发布:《Android系统多媒体进阶实战》🚀 优质专栏: Audio工程师进阶系列【原创干货持续更新中……】🚀 优质专栏: 多媒体系统工程师系列【原创干货持续更新中……】🚀 优质视频课程:AAOS车载系统+AOSP14系统攻城狮入门视频实战课 🚀 人生格言: 人生从来没有捷径,只有行动才是治疗恐惧

关于断言的部分用法

1、带变量的断言  systemVerilog assertion 中variable delay的使用,##[variable],带变量的延时(可变延时)_assertion中的延时-CSDN博客 2、until 的使用 systemVerilog assertion 中until的使用_verilog until-CSDN博客 3、throughout的使用   常用于断言和假设中的