DataGridView用法合集【精品】

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

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.xdnf.cn/news/1522987.html

如若内容造成侵权/违法违规/事实不符,请联系一条长河网进行投诉反馈,一经查实,立即删除!

相关文章

虚幻引擎VR游戏开发02 | 性能优化设置

常识&#xff1a;VR需要保持至少90 FPS的刷新率&#xff0c;以避免用户体验到延迟或晕眩感。以下是优化性能的一系列设置&#xff08;make sure the frame rate does not drop below a certain threshold&#xff09; In project setting-> &#xff08;以下十个设置都在pr…

基于php+vue+uniapp的医院预约挂号系统小程序

开发语言&#xff1a;PHP框架&#xff1a;phpuniapp数据库&#xff1a;mysql 5.7&#xff08;一定要5.7版本&#xff09;数据库工具&#xff1a;Navicat11开发软件&#xff1a;PhpStorm 系统展示 后台登录界面 管理员功能界面 用户管理 医生管理 科室分类管理 医生信息管理 预…

机器人外呼有哪些优势?

机器人外呼&#xff0c;作为一种结合了计算机技术和人工智能技术的自动化工具&#xff0c;具有多重显著优势。以下是其主要优势的详细阐述&#xff1a; ### 1. 高效性 * **大幅提升工作效率**&#xff1a;机器人外呼可以全天候、不间断地进行工作&#xff0c;不受时间、地点和…

【优质源码】3D多人在线游戏,前端ThreeJS,后端NodeJS

3D多人在线游戏 【源码】3D多人在线游戏源码&#xff0c;前端ThreeJS&#xff0c;后端NodeJS&#xff0c;完整源码。 游戏画面 启动方法 先启动服务器端。 在目录&#xff0c;3D-multi-player-main\3D-multi-player-main\nodeapps\blockland 中&#xff0c;运行&#xff1a…

Elasticsearch之原理详解

简介 ES是使用 Java 编写的一种开源搜索引擎&#xff0c;它在内部使用 Lucene 做索引与搜索&#xff0c;通过对 Lucene 的封装&#xff0c;隐藏了 Lucene 的复杂性&#xff0c;取而代之的提供一套简单一致的 RESTful API 然而&#xff0c;Elasticsearch 不仅仅是 Lucene&#…

设计模式及创建型模式-python版

1 架构模式与设计模式 架构模式搞层次的设计模式&#xff0c; 描述系统整体结构和组织方式&#xff0c;设计模式是针对某个问题的解决方案&#xff0c;是一种解决问题的思路。 2 设计模式的分类 2.1 创建型模式 单例模式&#xff0c;工厂方法模式&#xff0c;抽象工厂模式&…

JVM2-JVM组成、字节码文件、类的生命周期、类加载器

目录 Java虚拟机的组成 字节码文件 字节码文件打开方式 字节码文件的组成 基本信息 Magic魔数 主副版本号 常量池 字段 方法 属性 字节码常用工具 javap jclasslib插件 Arthas 类的生命周期 概述 加载阶段 连接阶段 验证 准备 解析 初始化阶段 类加载器…

linux 下一跳缓存,early demux(‌早期解复用)‌介绍

3.6版本以后的下一跳缓存 3.6版本移除了FIB查找前的路由缓存。这意味着每一个接收发送的skb现在都必须要进行FIB查找了。这样的好处是现在查找路由的代价变得稳定(consistent)了。3.6版本实际上是将FIB查找缓存到了下一跳(fib_nh)结构上&#xff0c;也就是下一跳缓存下一跳缓存…

ESP32无线WiFi芯片模组,设备物联网连接通信,产品智能化交互升级

在数字化浪潮的推动下&#xff0c;我们正步入一个万物互联的新时代。物联网&#xff08;IoT&#xff09;技术&#xff0c;作为连接物理世界与数字世界的桥梁&#xff0c;正逐渐渗透到我们生活的每一个角落。 乐鑫正通过其创新的无线WiFi芯片模组&#xff0c;为这些领域的发展提…

界面控件DevExpress中文教程:如何使用AI扩展Excel计算?

DevExpress WinForms拥有180组件和UI库&#xff0c;能为Windows Forms平台创建具有影响力的业务解决方案。DevExpress WinForms能完美构建流畅、美观且易于使用的应用程序&#xff0c;无论是Office风格的界面&#xff0c;还是分析处理大批量的业务数据&#xff0c;它都能轻松胜…

Elasticsearch的Restful风格API

前言&#xff1a;本博客仅作记录学习使用&#xff0c;部分图片出自网络&#xff0c;如有侵犯您的权益&#xff0c;请联系删除 1、Restful及JSON格式 RESTFUL是一种网络应用程序的设计风格和开发方式&#xff0c;基于HTTP&#xff0c;可以使用 XML 格式定义或 JSON 格式定义。R…

STM32CubeMX CAN收发数据

目录 一、CAN总线 1. 差分信号 2. CAN收发器 3. CAN帧结构 4. CAN波特率设置 5. 标识符筛选 二、CubeMX配置 三、Keil代码 一、CAN总线 CAN&#xff08;Controller Area Network&#xff0c;控制器局域网络&#xff09;是一种用于车辆、工业自动化等领域的通信协议&…

springboot博客系统

基于springbootvue实现的博客系统 &#xff08;源码L文ppt&#xff09;4-031 4 系统设计 博客系统的整体结构设计主要分为两大部分&#xff1a;管理员和博主。他们的权限不同&#xff0c;于是操作功能也有所不同。整体结构设计如图4-2所示。 图4-2 系统结构图 4.3 数据库设…

Unity(2022.3.41LTS) - 角色控制器和3D刚体

目录 一. 角色控制 二. 3D刚体 一. 角色控制 名称&#xff1a;功能&#xff1a;坡度限制将碰撞器限制为仅爬升比指示值更陡峭&#xff08;以度为单位&#xff09;的斜坡。步长偏移只有当楼梯离地面比指示值更近时&#xff0c;角色才会爬上楼梯。此值不应大于 Character Contr…

《CounTR: Transformer-based Generalised Visual Counting》CVPR2023

摘要 本论文考虑了通用视觉对象计数问题&#xff0c;目标是开发一个计算模型&#xff0c;用于计算任意语义类别的对象数量&#xff0c;使用任意数量的“样本”&#xff08;即可能为零样本或少样本计数&#xff09;。作者提出了一个新颖的基于Transformer的架构&#xff0c;称为…

shell 学习笔记:变量、字符串、注释

目录 1. 变量 1.1 定义使用变量 1.2 变量命名规则 1.3 只读变量 1.4 删除变量 1.5 变量类型 1.5.1 字符串变量 1.5.2 整数变量 1.5.3 数组变量 1.5.3.1 整数索引数组 1.5.3.2 关联数组 1.4 环境变量 1.5 特殊变量 2. 字符串 2.1 单引号字符串 2.2 双引…

【32项目】基于stm32f103c8t6WIFI远程监控智慧农业大棚(含完整代码)

目录 前言 设计背景 设计原理 所需材料 JW01二氧化碳传感器介绍 YL-69土壤湿度传感器介绍 PCB及原理图 部分代码&#xff08;完整代码见文章末尾&#xff09; 前言 随着农业现代化的发展&#xff0c;智慧农业的概念越来越受到重视。智慧农业利用物联网、大数据、人工智…

计算机网络 数据链路层2

ALOHA:想发就发 CSMA 载波监听多路访问协议 CS&#xff1a;载波监听&#xff0c;在发送数据之前检测总线上是否有其他计算机在发送数据 1-坚持CSMA:主机想发送消息&#xff0c;需要监听信道&#xff1b; 信道空闲则直接传输信息&#xff1b; 信道忙碌则一直监听&#xff0c;直…

【JavaWeb】JDBCDruidTomcat入门使用

本章使用技术版本&#xff1a; Tomcatv10.1.25 关于javaweb相关的其他技术&#xff0c;比如tomcat和maven&#xff0c;在我的主页记录了笔记&#xff0c;ajax我用的是本地笔记以后再考虑上传&#xff0c;前端三板斧我用的菜鸟教程文档 JDBC 初识 JDBC概念 JDBC 就是使用Jav…

【深度学习 transformer】使用pytorch 训练transformer 模型,hugginface 来啦

Hugging Face是一个致力于开源自然语言处理&#xff08;NLP&#xff09;和机器学习项目的社区。它由几个关键组件组成&#xff1a; Transformers&#xff1a;这是一个基于PyTorch的库&#xff0c;提供了各种预训练的NLP模型&#xff0c;如BERT、GPT、RoBERTa、DistilBERT等。它…