① 取得或者修改当前单元格的内容 ② 设定单元格只读 ③ 不显示最下面的新行 ④ 判断新增行 ⑤ 行的用户删除操作的自定义 ⑥ 行、列的隐藏和删除 ⑦ 禁止列或者行的Resize ⑧ 列宽和行高以及列头的高度和行头的宽度的自动调整 ⑨ 冻结列或行 ⑩ 列顺序的调整 ⑪ 行头列头的单元格 ⑫ 剪切板的操作 ⑬ 单元格的ToolTip的设置 ⑭ 右键菜单(Co
ntextMenu
Strip)的设置 ⑮ 单元格的边框、 网格线样式的设定 ⑯ 单元格表示
值的设定 ⑰ 用户输入时,单元格输入
值的设定 ⑱ 设定新加行的默认值 ① DataGridView 取得或者修改当前单元格的内容: GO TO TOP 当前单元格指的是 DataGridView 焦点所在的单元格,它可以通过 DataGridView 对象的 CurrentCell 属性取得。如果当前单元格不存在的时候,返回Nothing(C#是null) [VB.NET] ' 取得当前单元格内容 Console.WriteLine(DataGridView1.CurrentCel
l.value) ' 取得当前单元格的列 Index Console.WriteLine(DataGridView1.CurrentCel
l.columnInde
X) ' 取得当前单元格的行 Index Console.WriteLine(DataGridView1.CurrentCel
l.RowInde
X) [C#] // 取得当前单元格内容 Console.WriteLine(DataGridView1.CurrentCel
l.value); // 取得当前单元格的列 Index Console.WriteLine(DataGridView1.CurrentCel
l.columnInde
X); // 取得当前单元格的行 Index Console.WriteLine(DataGridView1.CurrentCel
l.RowInde
X); 另外,使用 DataGridView.CurrentCellAddress 属性(而不是直接访问单元格)来确定单元格所在的行:DataGridView.CurrentCellAddres
s.Y 和列: DataGridView.CurrentCellAddres
s.X 。这对于避免取消共享行的共享非常有用。 当前的单元格可以通过设定 DataGridView 对象的 CurrentCell 来改变。可以通过 CurrentCell 来设定 DataGridView 的激活单元格。将 CurrentCell 设为 Nothing(null) 可以取消激活的单元格。 [VB.NET] ' 设定 (0,0) 为当前单元格 DataGridView1.CurrentCell = DataGridView1(0,0) [C#] // 设定 (0,0) 为当前单元格 DataGridView1.CurrentCell = DataGridView1[0,0]; 在整行选中模式开启时,你也可以通过 CurrentCell 来设定选定行。 /
**//// <sum
Mary> /// 向下遍历 /// </sum
Mary> /// <param name="sender"></param> /// <param name="e"></param> private void button4_Click(ob
ject sender,EventArgs
E) ...
{ int row = thi
s.dataGridView1.CurrentRow.Index + 1; if (row > thi
s.dataGridView1.RowCount - 1) row = 0; thi
s.dataGridView1.CurrentCell = thi
s.dataGridView1[0,row]; } /
**//// <sum
Mary> /// 向上遍历 /// </sum
Mary> /// <param name="sender"></param> /// <param name="e"></param> private void button5_Click(ob
ject sender,EventArgs
E) ...
{ int row = thi
s.dataGridView1.CurrentRow.Index - 1; if (row < 0) row = thi
s.dataGridView1.RowCount - 1; thi
s.dataGridView1.CurrentCell = thi
s.dataGridView1[0,row]; } * 注意: thi
s.dataGridView 的索引器的参数是:
columnIndex,rowIndex 或是
columnName,rowIndex 这与习惯不同。 -------------------------------------------------------------------------------- ② DataGridView 设定单元格只读: GO TO TOP 1) 使用 ReadOnly 属性 ⇒ 如果希望,DataGridView 内所有单元格都不可编辑, 那么只要: [VB.NET] ' 设置 DataGridView1 为只读 DataGridView1.ReadOnly = True [C#] // 设置 DataGridView1 为只读 DataGridView1.ReadOnly = true;此时,用户的新增行操作和删除行操作也被屏蔽了。 ⇒ 如果希望,DataGridView 内某个单元格不可编辑, 那么只要: [VB.NET] ' 设置 DataGridView1 的第2列整列单元格为只读 DataGridView1.
columns
(1).ReadOnly = True ' 设置 DataGridView1 的第3行整行单元格为只读 DataGridView1.Rows(2).ReadOnly = True ' 设置 DataGridView1 的[0,0]单元格为只读 DataGridView1(0,0).ReadOnly = True [C#] // 设置 DataGridView1 的第2列整列单元格为只读 DataGridView1.
columns[1].ReadOnly = true; // 设置 DataGridView1 的第3行整行单元格为只读 DataGridView1.Rows[2].ReadOnly = true; // 设置 DataGridView1 的[0,0]单元格为只读 DataGridView1[0,0].ReadOnly = true; 2) 使用 EditMode 属性 DataGridView.EditMode 属性被设置为 DataGridViewEditMode.EditProgr
AMMatically 时,用户就不能手动编辑单元格的内容了。但是可以通过程序,调用 DataGridView
.beginEdit 方法,使单元格进入编辑模式进行编辑。 [VB.NET] DataGridView1.EditMode = DataGridViewEditMode.EditProgr
AMMatically [C#] DataGridView1.EditMode = DataGridViewEditMode.EditProgr
AMMatically; 3) 根据条件设定单元格的不可编辑状态 当一个一个的通过单元格坐标设定单元格 ReadOnly 属性的方法太麻烦的时候,你可以通过 CellBeginEdit 事件来取消单元格的编辑。 [VB.NET] 'CellBeginEdit 事件处理方法 Private Sub DataGridView1_CellBeginEdit(ByVal sender As Ob
ject,_ ByVal e As DataGridViewCellCancelEventArgs) _ Handles DataGridView1.CellBeginEdit Dim dgv As DataGridView = CType(sender,DataGridView) ' 是否可以进行编辑的条件检查
if Dgv.
columns(e.
columnInde
X).Name = "
column1" AndAlso _ Not CBool(dgv("
column2",e.RowInde
X).
value) Then ' 取消编辑 e.Cancel = True End If End Sub [C#] // CellBeginEdit 事件处理方法 private void DataGridView1_CellBeginEdit(ob
ject sender,DataGridViewCellCancelEventArgs
E) { DataGridView dgv = (DataGridView)sender; //是否可以进行编辑的条件检查 if (dgv.
columns[e.
columnIndex].Name == "
column1" && !(bool)dgv["
column2",e.RowIndex].
value) { // 取消编辑 e.Cancel = true; } } -------------------------------------------------------------------------------- ③ DataGridView 不显示最下面的新行: GO TO TOP 通常 DataGridView 的最下面一行是用户新追加的行(行头显示 * )。如果不想让用户新追加行即不想显示该新行,可以将 DataGridView 对象的 AllowUser
toaddRows 属性设置为
false。 [VB.NET] ' 设置用户不能手动给 DataGridView1 添加新行 DataGridView1.AllowUser
toaddRows =
false [C#] // 设置用户不能手动给 DataGridView1 添加新行 DataGridView1.AllowUser
toaddRows =
false; 但是,可以通过程序: DataGridViewRowCollection.Add 为 DataGridView 追加新行。 补足: 如果 DataGridView 的 Data
source 绑定的是 DataView,还可以通过设置 DataView.AllowAdd 属性为
false 来达到同样的效果。 -------------------------------------------------------------------------------- ④ DataGridView 判断新增行: GO TO TOP DataGridView的AllowUser
toaddRows属性为True时也就是允许用户追加新行的场合下,DataGridView的最后一行就是新追加的行(*行)。使用 DataGridViewRow.IsNewRow 属性可以判断哪一行是新追加的行。另外,通过DataGridView.NewRowIndex
可以获取新行的行序列号。在没有新行的时候,NewRowIndex = -1。 [VB.NET]
if DataGridView1.CurrentRow.IsNewRow Then Console.WriteLine("当前行为新追加行。") Else Console.WriteLine("当前行不是新追加行。") End If -------------------------------------------------------------------------------- ⑤ DataGridView 行的用户删除操作的自定义: GO TO TOP 1) 无条件的限制行删除操作。 默认时,DataGridView 是允许用户进行行的删除操作的。如果设置 DataGridView对象的AllowUserTo
deleteRows属性为
false 时, 用户的行删除操作就被禁止了。 [VB.NET] ' 禁止DataGridView1的行删除操作。 DataGridView1.AllowUserTo
deleteRows =
false [C#] // 禁止DataGridView1的行删除操作。 DataGridView1.AllowUserTo
deleteRows =
false; 但是,通过 DataGridViewRowCollection.Remove 还是可以进行行的删除。 补足: 如果 DataGridView 绑定的是 DataView 的话,通过 DataView.Allow
delete 也可以控制行的删除。 2) 行删除时的条件判断处理。 用户在删除行的时候,将会引发 DataGridView.User
deletingRow 事件。 在这个事件里,可以判断条件并取消删除操作。 [VB.NET] ' DataGridView1 的 User
deletingRow 事件 Private Sub DataGridView1_User
deletingRow(ByVal sender As Ob
ject,_ ByVal e As DataGridViewRowCancelEventArgs) _ Handles DataGridView1.User
deletingRow ' 删除前的用户确认。 If
messageBox.Show("确认要删除该行数据吗?","删除确认",_
messageBoxButton
s.OKCancel,
messageBoxIcon.Question) <> _ Window
s.Form
s.DialogResult
.oK Then ' 如果不是 OK,则取消。 e.Cancel = True End If End Sub [C#] // DataGridView1 的 User
deletingRow 事件 private void DataGridView1_User
deletingRow( ob
ject sender,DataGridViewRowCancelEventArgs
E) { // 删除前的用户确认。 if (
messageBox.Show("确认要删除该行数据吗?",
messageBoxButton
s.OKCancel,
messageBoxIcon.Question)
!= DialogResult
.oK)
{ // 如果不是 OK,则取消。 e.Cancel = true; } } -------------------------------------------------------------------------------- ⑥ DataGridView 行、列的隐藏和删除: GO TO TOP 1) 行、列的隐藏 [VB.NET] ' DataGridView1的第一列隐藏 DataGridView1.
columns(0).Visible =
false ' DataGridView1的第一行隐藏 DataGridView1.Rows(0).Visible =
false [C#] // DataGridView1的第一列隐藏 DataGridView1.
columns
[0].Visible =
false; // DataGridView1的第一行隐藏 DataGridView1.Rows
[0].Visible =
false; 2) 行头、列头的隐藏 [VB.NET] ' 列头隐藏 DataGridView1.
columnHeadersVisible =
false ' 行头隐藏 DataGridView1.RowHeadersVisible =
false [C#] // 列头隐藏 DataGridView1.
columnHeadersVisible =
false; // 行头隐藏 DataGridView1.RowHeadersVisible =
false; 3) 行和列的删除 [VB.NET] ' 删除名为"
column1"的列 DataGridView1.
column
s.Remove("
column1") ' 删除第一列 DataGridView1.
column
s.RemoveAt(0) ' 删除第一行 DataGridView1.Row
s.RemoveAt(0) [C#] ' 删除名为"
column1"的列 DataGridView1.
column
s.Remove("
column1"
); ' 删除第一列 DataGridView1.
column
s.RemoveAt(0
); ' 删除第一行 DataGridView1.Row
s.RemoveAt(0
); 4) 删除选中行 [VB.NET] For Each r As DataGridViewRow In DataGridView1.
SELEctedRows If Not r.IsNewRow Then DataGridView1.Row
s.Remove(r) End If Next [C#] foreach (DataGridViewRow r in DataGridView1.
SELEctedRows)
{ if (!r.IsNewRow)
{ DataGridView1.Row
s.Remove(r
); } } -------------------------------------------------------------------------------- ⑦ DataGridView 禁止列或者行的Resize: GO TO TOP 1) 禁止所有的列或者行的Resize [VB.NET] ' 禁止用户改变DataGridView1的所有列的列宽 DataGridView1.AllowUserToResize
columns =
false '禁止用户改变DataGridView1の所有行的行高 DataGridView1.AllowUserToResizeRows =
false [C#] // 禁止用户改变DataGridView1的所有列的列宽 DataGridView1.AllowUserToResize
columns =
false; //禁止用户改变DataGridView1の所有行的行高 DataGridView1.AllowUserToResizeRows =
false; 但是可以通过 DataGridView
column.Width 或者 DataGridViewRow.Height 属性设定列宽和行高。 2) 禁止指定行或者列的Resize [VB.NET] ' 禁止用户改变DataGridView1的第一列的列宽 DataGridView1.
columns(0).Resizable = DataGridViewTriState.
false ' 禁止用户改变DataGridView1的第一列的行宽 DataGridView1.Rows(0).Resizable = DataGridViewTriState.
false [C#] // 禁止用户改变DataGridView1的第一列的列宽 DataGridView1.
columns
[0].Resizable = DataGridViewTriState.
false; // 禁止用户改变DataGridView1的第一列的行宽 DataGridView1.Rows
[0].Resizable = DataGridViewTriState.
false; ⇒ 关于 NoSet 当 Resizable 属性设为 DataGridViewTriState.NotSet 时, 实际上会默认以 DataGridView 的 AllowUserToResize
columns 和 AllowUserToResizeRows 的属性值进行设定。比如: DataGridView.AllowUserToResize
columns =
false 且 Resizable 是 NoSet 设定时,Resizable =
false 。 判断 Resizable 是否是继承设定了 DataGridView 的 AllowUserToResize
columns 和 AllowUserToResizeRows 的属性值, 可以根据 State 属性判断。如果 State 属性含有 ResizableSet,那么说明没有继承设定。 3) 列宽和行高的最小
值的设定 [VB.NET] ' 第一列的最小列宽设定为 100 DataGridView1.
columns(0).MinimumWidth = 100 ' 第一行的最小行高设定为 50 DataGridView1.Rows(0).MinimumHeight = 50 [C#] // 第一列的最小列宽设定为 100 DataGridView1.
columns
[0].MinimumWidth = 100; // 第一行的最小行高设定为 50 DataGridView1.Rows
[0].MinimumHeight = 50; 4) 禁止用户改变行头的宽度以及列头的高度 [VB.NET] ' 禁止用户改变列头的高度 DataGridView1.
columnHeadersHeightSizeMode = _ DataGridView
columnHeadersHeightSizeMode.DisableResizing ' 禁止用户改变行头的宽度 DataGridView1.RowHeadersWidthSizeMode = _ DataGridViewRowHeadersWidthSizeMode.EnableResizing [C#] // 禁止用户改变列头的高度 DataGridView1.
columnHeadersHeightSizeMode = DataGridView
columnHeadersHeightSizeMode.DisableResizing; // 禁止用户改变行头的宽度 DataGridView1.RowHeadersWidthSizeMode = DataGridViewRowHeadersWidthSizeMode.EnableResizing; -------------------------------------------------------------------------------- ⑧ DataGridView 列宽和行高自动调整的设定: GO TO TOP 1) 设定行高和列宽自动调整 [VB.NET] ' 设定包括Header和所有单元格的列宽自动调整 DataGridView1.AutoSize
columnsMode = DataGridViewAutoSize
columnsMode.AllCells ' 设定包括Header和所有单元格的行高自动调整 DataGridView1.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells [C#] // 设定包括Header和所有单元格的列宽自动调整 DataGridView1.AutoSize
columnsMode = DataGridViewAutoSize
columnsMode.AllCells; // 设定包括Header和所有单元格的行高自动调整 DataGridView1.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells; AutoSize
columnsMode 属性的设定值枚举请参照 msdn 的 DataGridViewAutoSizeRowsMode 说明。 2)指定列或行自动调整 [VB.NET] ' 第一列自动调整 DataGridView1.
columns(0).AutoSizeMode = _ DataGridViewAutoSize
columnMode.DisplayedCells [C#] // 第一列自动调整 DataGridView1.
columns
[0].AutoSizeMode = DataGridViewAutoSize
columnMode.DisplayedCells; AutoSizeMode 设定为 NotSet 时, 默认继承的是 DataGridView.AutoSize
columnsMode 属性。 3) 设定列头的高度和行头的宽度自动调整 [VB.NET] ' 设定列头的宽度可以自由调整 DataGridView1.
columnHeadersHeightSizeMode = _ DataGridView
columnHeadersHeightSizeMode.AutoSize ' 设定行头的宽度可以自由调整 DataGridView1.RowHeadersWidthSizeMode = _ DataGridViewRowHeadersWidthSizeMode.AutoSizeToAllHeaders [C#] // 设定列头的宽度可以自由调整 DataGridView1.
columnHeadersHeightSizeMode = DataGridView
columnHeadersHeightSizeMode.AutoSize; // 设定行头的宽度可以自由调整 DataGridView1.RowHeadersWidthSizeMode = DataGridViewRowHeadersWidthSizeMode.AutoSizeToAllHeaders; 4) 随时自动调整 a, 临时的,让列宽自动调整,这和指定AutoSize
columnsMode属性一样。 [VB.NET] ' 让 DataGridView1 的所有列宽自动调整一下。 DataGridView1.AutoResize
columns(DataGridViewAutoSize
columnsMode.AllCells) ' 让 DataGridView1 的第一列的列宽自动调整一下。 DataGridView1.AutoResize
column(0,DataGridViewAutoSize
columnMode.AllCells) [C#] // 让 DataGridView1 的所有列宽自动调整一下。 DataGridView1.AutoResize
columns(DataGridViewAutoSize
columnsMode.AllCells
); // 让 DataGridView1 的第一列的列宽自动调整一下。 DataGridView1.AutoResize
column(0,DataGridViewAutoSize
columnMode.AllCells
);上面调用的 AutoResize
columns 和 AutoResize
column 当指定的是DataGridViewAutoSize
columnMode.AllCells 的时候, 参数
可以省略。即: DataGridView1.AutoResize
column(0) 和 DataGridView1.AutoResize
columns() b,临时的,让行高自动调整 [VB.NET] ' 让 DataGridView1 的所有行高自动调整一下。 DataGridView1.AutoResizeRows(DataGridViewAutoSizeRowsMode.AllCells) ' 让 DataGridView1 的第一行的行高自动调整一下。 DataGridView1.AutoResizeRow(0,DataGridViewAutoSizeRowMode.AllCells) [C#] // 让 DataGridView1 的所有行高自动调整一下。 DataGridView1.AutoResizeRows(DataGridViewAutoSizeRowsMode.AllCells
); //让 DataGridView1 的第一行的行高自动调整一下。 DataGridView1.AutoResizeRow(0,DataGridViewAutoSizeRowMode.AllCells
);上面调用的 AutoResizeRows 和 AutoResizeRow 当指定的是DataGridViewAutoSizeRowMode.AllCells 的时候, 参数
可以省略。即:DataGridView1.AutoResizeRow (0) 和 DataGridView1.AutoResizeRows() c,临时的,让行头和列头自动调整 [VB.NET] ' 列头高度自动调整 DataGridView1.AutoResize
columnHeadersHeight() ' 行头宽度自动调整 DataGridView1.AutoResizeRowHeadersWidth( _ DataGridViewRowHeadersWidthSizeMode.AutoSizeToAllHeaders) [C#] // 列头高度自动调整 DataGridView1.AutoResize
columnHeadersHeight(
); // 行头宽度自动调整 DataGridView1.AutoResizeRowHeadersWidth( DataGridViewRowHeadersWidthSizeMode.AutoSizeToAllHeaders
); 关于性能: 通过 AutoSize
columnsMode 或者 AutoSizeRowsMode 属性所指定的单元格进行自动调整时,如果调整次数过于多那么将可能导致性能下降,尤其是在行和列数比较多的情况下。在这时用 DisplayedCells 代替 AllCells 能减少非所见的单元格的调整,从而提高性能。 -------------------------------------------------------------------------------- ⑨ DataGridView 冻结列或行 GO TO TOP 1) 列冻结 DataGridView
column.Frozen 属性为 True 时, 该列左侧的所有列被固定, 横向滚动时固定列不随滚动条滚动而左右移动。这对于重要列固定显示很有用。 [VB.NET] ' DataGridView1的左侧2列固定 DataGridView1.
columns
(1).Frozen = True [C#] // DataGridView1的左侧2列固定 DataGridView1.
columns[1].Frozen = true; 但是,DataGridView.AllowUserToOrder
columns = True 时,固定列不能移动到非固定列, 反之亦然。 2) 行冻结 DataGridViewRow.Frozen 属性为 True 时, 该行上面的所有行被固定, 纵向滚动时固定行不随滚动条滚动而上下移动。 [VB.NET] ' DataGridView1 的上3行固定 DataGridView1.Rows(2).Frozen = True [C#] // DataGridView1 的上3行固定 DataGridView1.Rows[2].Frozen = true; -------------------------------------------------------------------------------- ⑩ DataGridView 列顺序的调整 GO TO TOP 设定 DataGridView 的 AllowUserToOrder
columns 为 True 的时候, 用户可以自由调整列的顺序。 当用户改变列的顺序的时候,其本身的 Index 不会改变,但是 DisplayIndex 改变了。你也可以通过程序改变 DisplayIndex 来改变列的顺序。 列顺序发生改变时会引发
columnDisplayIndexChanged 事件: [VB.NET] ' DataGridView1的
columnDisplayIndexChanged事件处理方法 Private Sub DataGridView1_
columnDisplayIndexChanged(ByVal sender As Ob
ject,_ ByVal e As DataGridView
columnEventArgs) _ Handles DataGridView1.
columnDisplayIndexChanged Console.WriteLine("
{0} 的位置改变到
{1} 。",_ e.
column.Name,e.
column.DisplayInde
X) End Sub [C#] // DataGridView1的
columnDisplayIndexChanged事件处理方法 private void DataGridView1_
columnDisplayIndexChanged(ob
ject sender,DataGridView
columnEventArgs
E) { Console.WriteLine("
{0} 的位置改变到
{1} ",e.
column.Name,e.
column.DisplayInde
X); } -------------------------------------------------------------------------------- ⑪ DataGridView 行头列头的单元格 GO TO TOP [VB.NET] ' DataGridView1的第一列列头内容 DataGridView1.
columns(0).HeaderCel
l.Value = "第一列" ' DataGridView1的第一行行头内容 DataGridView1.Rows(0).HeaderCel
l.Value = "第一行" ' DataGridView1的左上头部单元内容 DataGridView1.TopLeftHeaderCel
l.Value = "左上" [C#] // 改变DataGridView1的第一列列头内容 DataGridView1.
columns
[0].HeaderCel
l.Value = "第一列"; // 改变DataGridView1的第一行行头内容 DataGridView1.Rows
[0].HeaderCel
l.Value = "第一行"; // 改变DataGridView1的左上头部单元内容 DataGridView1.TopLeftHeaderCel
l.Value = "左上"; 另外你也可以通过 HeaderText 来改变他们的内容。 [VB.NET] ' 改变DataGridView1的第一列列头内容 DataGridView1.
columns(0).HeaderText = "第一列" [C#] // 改变DataGridView1的第一列列头内容 DataGridView1.
columns
[0].HeaderText = "第一列"; -------------------------------------------------------------------------------- ⑫ DataGridView 剪切板的操作 GO TO TOP DataGridView.ClipboardCop
ymode 属性被设定为 DataGridViewClipboardCop
ymode.Disable 以外的情况时,「Ctrl + C」 按下的时候,被选择的单元格的内容会拷贝到系统剪切板内。格式有: Text, UnicodeText,Html, CommaSeparatedValue。可以直接粘贴到 Excel 内。 ClipboardCop
ymode 还可以设定 Header部分是否拷贝: EnableAlwaysIncludeHeaderText 拷贝Header部分、EnableWithoutHeaderText 则不拷贝。默认是 EnableWithAutoHeaderText , Header 如果选择了的话,就拷贝。 1) 编程方式实现剪切板的拷贝 Clipboard.SetDataOb
ject(DataGridView1.GetClipboardContent()) 2) DataGridView 的数据粘贴 实现剪切板的拷贝比较容易,但是实现 DataGridView 的直接粘贴就比较难了。「Ctrl + V」按下进行粘贴时,DataGridView 没有提供方法,只能自己实现。 以下,是粘贴时简单的事例代码,将拷贝数据粘贴到以选择单元格开始的区域内。 [VB.NET] ' 当前单元格是否选择的判断
if DataGridView1.CurrentCell Is Nothing Then Return End
if Dim insertRowIndex As
Integer = DataGridView1.CurrentCel
l.RowIndex ' 获取剪切板的内容,并按行分割 Dim pasteText As
String = Clipboard.GetText() If
String.IsNullOrEmpty(pasteText) Then Return End If pasteText = pasteText.
replace(vbCrLf,vbLf) pasteText = pasteText.
replace(vbCr,vbLf) pasteText.TrimEnd(New Char()
{vbLf}) Dim li
nes As
String() = pasteText.Split(vbLf) Dim isHeader As
Boolean = True For Each line As
String In li
nes ' 是否是列头 If isHeader Then isHeader =
false Else ' 按 Tab 分割数据 Dim vals As
String() = line.Split(ControlChar
s.Tab) ' 判断列数是否统一 If val
s.Length - 1 <> DataGridView1.
columnCount Then Throw New ApplicationException("粘贴的列数不正确。") End If Dim row As DataGridViewRow = DataGridView1.Rows(insertRowInde
X) ' 行头设定 row.HeaderCel
l.Value = vals(0) ' 单元格内容设定 Dim i As
Integer For i = 0 To row.Cell
s.Count - 1 row.Cells(i).Value = vals((i + 1)) Next i ' DataGridView的行索引+1 insertRowIndex += 1 End If Next line [C#] //当前单元格是否选择的判断 if (DataGridView1.CurrentCell == null) return; int insertRowIndex = DataGridView1.CurrentCel
l.RowIndex; // 获取剪切板的内容,并按行分割
String pasteText = Clipboard.GetText(
); if (
String.IsNullOrEmpty(pasteText)) return; pasteText = pasteText.
replace(" "," "
); pasteText = pasteText.
replace(' ',' '
); pasteText.TrimEnd(new char[]
{ ' ' }
); String[] li
nes = pasteText.Split(' '
); bool isHeader = true; foreach (
String line in li
nes)
{ // 是否是列头 if (isHeader)
{ isHeader =
false; con
Tinue; } // 按 Tab 分割数据
String[] vals = line.Split(' '
); // 判断列数是否统一 if (val
s.Length - 1
!= DataGridView1.
columnCount) throw new ApplicationException("粘贴的列数不正确。"
); DataGridViewRow row = DataGridView1.Rows[insertRowIndex]; // 行头设定 row.HeaderCel
l.Value = vals
[0]; // 单元格内容设定 for (int i = 0; i < row.Cell
s.Count; i++)
{ row.Cells[i].Value = vals[i + 1]; } // DataGridView的行索引+1 insertRowIndex++; } -------------------------------------------------------------------------------- ⑬ DataGridView 单元格的ToolTip的设置 GO TO TOP DataGridView.ShowCellToolTips = True 的情况下, 单元格的 ToolTip 可以表示出来。对于单元格窄小,无法完全显示的单元格, ToolTip 可以显示必要的信息。 1) 设定单元格的ToolTip内容 [VB.NET] ' 设定单元格的ToolTip内容 DataGridView1(0,0).ToolTipText = "该单元格的内容不能修改" ' 设定列头的单元格的ToolTip内容 DataGridView1.
columns(0).ToolTipText = "该列只能输入数字" ' 设定行头的单元格的ToolTip内容 DataGridView1.Rows(0).HeaderCel
l.ToolTipText = "该行单元格内容不能修改" [C#] // 设定单元格的ToolTip内容 DataGridView1[0,0].ToolTipText = "该单元格的内容不能修改"; // 设定列头的单元格的ToolTip内容 DataGridView1.
columns
[0].ToolTipText = "该列只能输入数字"; // 设定行头的单元格的ToolTip内容 DataGridView1.Rows
[0].HeaderCel
l.ToolTipText = "该行单元格内容不能修改"; 2) CellToolTipTextNeeded 事件 在批量的单元格的 ToolTip 设定的时候,一个一个指定那么设定的效率比较低, 这时候可以利用 CellToolTipTextNeeded 事件。当单元格的 ToolTipText 变化的时候也会引发该事件。但是,当DataGridView的Data
source被指定且Virua
lmode=True的时候,该事件不会被引发。 [VB.NET] ' CellToolTipTextNeeded事件处理方法 Private Sub DataGridView1_CellToolTipTextNeeded(ByVal sender As Ob
ject,_ ByVal e As DataGridViewCellToolTipTextNeededEventArgs) _ Handles DataGridView1.CellToolTipTextNeeded e.ToolTipText = e.
columnIndex.To
String() + "," + e.RowIndex.To
String() End Sub [C#] // CellToolTipTextNeeded事件处理方法 private void DataGridView1_CellToolTipTextNeeded(ob
ject sender,DataGridViewCellToolTipTextNeededEventArgs
E) { e.ToolTipText = e.
columnIndex.To
String() + "," + e.RowIndex.To
String(
); } -------------------------------------------------------------------------------- ⑭ DataGridView 的右键菜单(Co
ntextMenu
Strip) GO TO TOP DataGridView,DataGridView
column,DataGridViewRow,DataGridViewCell 有 Co
ntextMenu
Strip 属性。可以通过设定 Co
ntextMenu
Strip 对象来控制 DataGridView 的右键菜单的显示。 DataGridView
column 的 Co
ntextMenu
Strip 属性设定了 除了列头以外的单元格的右键菜单。 DataGridViewRow 的 Co
ntextMenu
Strip 属性设定了除了行头以外的单元格的右键菜单。DataGridViewCell 的 Co
ntextMenu
Strip 属性设定了指定单元格的右键菜单。 [VB.NET] ' DataGridView 的 Co
ntextMenu
Strip 设定 DataGridView1.Co
ntextMenu
Strip = Me.Co
ntextMenu
Strip1 ' 列的 Co
ntextMenu
Strip 设定 DataGridView1.
columns(0).Co
ntextMenu
Strip = Me.Co
ntextMenu
Strip2 ' 列头的 Co
ntextMenu
Strip 设定 DataGridView1.
columns(0).HeaderCel
l.Co
ntextMenu
Strip = Me.Co
ntextMenu
Strip2 ' 行的 Co
ntextMenu
Strip 设定 DataGridView1.Rows(0).Co
ntextMenu
Strip = Me.Co
ntextMenu
Strip3 ' 单元格的 Co
ntextMenu
Strip 设定 DataGridView1(0,0).Co
ntextMenu
Strip = Me.Co
ntextMenu
Strip4 [C#] // DataGridView 的 Co
ntextMenu
Strip 设定 DataGridView1.Co
ntextMenu
Strip = thi
s.Co
ntextMenu
Strip1; // 列的 Co
ntextMenu
Strip 设定 DataGridView1.
columns
[0].Co
ntextMenu
Strip = thi
s.Co
ntextMenu
Strip2; // 列头的 Co
ntextMenu
Strip 设定 DataGridView1.
columns
[0].HeaderCel
l.Co
ntextMenu
Strip = thi
s.Co
ntextMenu
Strip2; // 行的 Co
ntextMenu
Strip 设定 DataGridView1.Rows
[0].Co
ntextMenu
Strip = thi
s.Co
ntextMenu
Strip3; // 单元格的 Co
ntextMenu
Strip 设定 DataGridView1[0,0].Co
ntextMenu
Strip = thi
s.Co
ntextMenu
Strip4; 对于单元格上的右键菜单的设定,优先顺序是: Cell > Row >
column > DataGridView ⇒ CellCo
ntextMenu
StripNeeded、RowCo
ntextMenu
StripNeeded 事件 利用 CellCo
ntextMenu
StripNeeded 事件可以设定单元格的右键菜单,尤其
但需要右键菜单根据单元格
值的变化而变化的时候。比起使用循环遍历,使用该事件来设定右键菜单的效率更高。但是,在DataGridView使用了Data
source绑定而且是Virtua
lmode的时候,该事件将不被引发。 [VB.NET] ' CellCo
ntextMenu
StripNeeded事件处理方法 Private Sub DataGridView1_CellCo
ntextMenu
StripNeeded( _ ByVal sender As Ob
ject,_ ByVal e As DataGridViewCellCo
ntextMenu
StripNeededEventArgs) _ Handles DataGridView1.CellCo
ntextMenu
StripNeeded Dim dgv As DataGridView = CType(sender,DataGridView) If e.RowIndex < 0 Then ' 列头的Co
ntextMenu
Strip设定 e.Co
ntextMenu
Strip = Me.Co
ntextMenu
Strip1 ElseIf e.
columnIndex < 0 Then ' 行头的Co
ntextMenu
Strip设定 e.Co
ntextMenu
Strip = Me.Co
ntextMenu
Strip2 ElseIf TypeOf (dgv(e.
columnIndex,e.RowInde
X).
value) Is
Integer Then ' 如果单元格值是整数时 e.Co
ntextMenu
Strip = Me.Co
ntextMenu
Strip3 End If End Sub [C#] // CellCo
ntextMenu
StripNeeded事件处理方法 private void DataGridView1_CellCo
ntextMenu
StripNeeded(ob
ject sender,DataGridViewCellCo
ntextMenu
StripNeededEventArgs
E) { DataGridView dgv = (DataGridView)sender; if (e.RowIndex < 0)
{ // 列头的Co
ntextMenu
Strip设定 e.Co
ntextMenu
Strip = thi
s.Co
ntextMenu
Strip1; } else if (e.
columnIndex < 0)
{ // 行头的Co
ntextMenu
Strip设定 e.Co
ntextMenu
Strip = thi
s.Co
ntextMenu
Strip2; } else if (dgv[e.
columnIndex,e.RowIndex].Value is
int) { // 如果单元格值是整数时 e.Co
ntextMenu
Strip = thi
s.Co
ntextMenu
Strip3; } } 同样,可以通过 RowCo
ntextMenu
StripNeeded 事件来设定行的右键菜单。 [VB.NET] ' RowCo
ntextMenu
StripNeeded事件处理方法 Private Sub DataGridView1_RowCo
ntextMenu
StripNeeded( _ ByVal sender As Ob
ject,_ ByVal e As DataGridViewRowCo
ntextMenu
StripNeededEventArgs) _ Handles DataGridView1.RowCo
ntextMenu
StripNeeded Dim dgv As DataGridView = CType(sender,DataGridView) ' 当"
column1"列是Bool型且为True时、设定其的Co
ntextMenu
Strip Dim boolVal As Ob
ject = dgv("
column1",e.RowInde
X).Value Console.WriteLine(boolVal) If TypeOf boolVal Is
Boolean AndAlso CBool(boolVal) Then e.Co
ntextMenu
Strip = Me.Co
ntextMenu
Strip1 End If End Sub [C#] // RowCo
ntextMenu
StripNeeded事件处理方法 private void DataGridView1_RowCo
ntextMenu
StripNeeded(ob
ject sender,DataGridViewRowCo
ntextMenu
StripNeededEventArgs
E) { DataGridView dgv = (DataGridView)sender; // 当"
column1"列是Bool型且为True时、设定其的Co
ntextMenu
Strip ob
ject boolVal = dgv["
column1",e.RowIndex].Value; Console.WriteLine(boolVal
); if (boolVal is bool && (bool)boolVal)
{ e.Co
ntextMenu
Strip = thi
s.Co
ntextMenu
Strip1; } } CellCo
ntextMenu
StripNeeded 事件处理方法的参数中、「e.
columnIndex=-1」表示行头、「e.RowIndex=-1」表示列头。RowCo
ntextMenu
StripNeeded则不存在「e.RowIndex=-1」的情况。 -------------------------------------------------------------------------------- ⑮ DataGridView 的单元格的边框、 网格线样式的设定 GO TO TOP 1) DataGridView 的边框线样式的设定 DataGridView 的边框线的样式是通过 DataGridView
.borderstyle 属性来设定的。 B
orderstyle 属性设定值是一个 B
orderstyle 枚举: FixedSingle(单线,默认)、Fixed3D、None。 2) 单元格的边框线样式的设定 单元格的边框线的样式是通过 DataGridView.CellB
orderstyle 属性来设定的。 CellB
orderstyle 属性设定值是 DataGridViewCellB
orderstyle 枚举。(详细参见 MSDN) 另外,通过 DataGridView.
columnHeadersB
orderstyle 和 RowHeadersB
orderstyle 属性可以修改 DataGridView 的头部的单元格边框线样式。 属性设定值是 DataGridViewHeaderB
orderstyle 枚举。(详细参见 MSDN) 3) 单元格的边框颜色的设定 单元格的边框线的颜色可以通过 DataGridView.GridColor 属性来设定的。默认是 ControlDarkDark 。但是只有在 CellB
orderstyle 被设定为 Single、SingleHorizontal、SingleVertical 的条件下才能改变其边框线的颜色。同样,
columnHeadersB
orderstyle 以及 RowHeadersB
orderstyle 只有在被设定为 Single 时,才能改变颜色。 4) 单元格的上下左右的边框线式样的单独设定 CellB
orderstyle只能设定单元格全部边框线的式样。要单独改变单元格某一边边框式样的话,
需要用到DataGridView.AdvancedCellB
orderstyle属性。如示
例: [VB.NET] ' 单元格的上边和左边线设为二重线 ' 单元格的下边和右边线设为单重线 DataGridView1.AdvancedCellB
orderstyle.Top = _ DataGridViewAdvancedCellB
orderstyle.InsetDouble DataGridView1.AdvancedCellB
orderstyle.Right = _ DataGridViewAdvancedCellB
orderstyle.Inset DataGridView1.AdvancedCellB
orderstyle
.bottom = _ DataGridViewAdvancedCellB
orderstyle.Inset DataGridView1.AdvancedCellB
orderstyle.Left = _ DataGridViewAdvancedCellB
orderstyle.InsetDouble 同样,设定行头单元格的属性是: AdvancedRowHeadersB
orderstyle, 设定列头单元格属性是:Advanced
columnHeadersB
orderstyle。 -------------------------------------------------------------------------------- ⑯ DataGridView 单元格表示
值的自定义 GO TO TOP 通过CellFormat
Ting事件,
可以自定义单元格的表示值。(比如:值为Error的时候,单元格被设定为红色) 下面的示
例:将“Colmn1”列的值改为大写。 [VB.NET] 'CellFormat
Ting 事件处理方法 Private Sub DataGridView1_CellFormat
Ting(ByVal sender As Ob
ject,_ ByVal e As DataGridViewCellFormat
TingEventArgs) _ Handles DataGridView1.CellFormat
Ting Dim dgv As DataGridView = CType(sender,DataGridView) ' 如果单元格是“
column1”列的单元格
if Dgv.
columns(e.
columnInde
X).Name = "
column1" AndAlso _ TypeOf e.Value Is
String Then ' 将单元格值改为大写 Dim str As
String = e.Value.To
String() e.Value = str.ToUpper() ' 应用该Format,Format完毕。 e.Format
TingApplied = True End If End Sub [C#] //CellFormat
Ting 事件处理方法 private void DataGridView1_CellFormat
Ting(ob
ject sender,DataGridViewCellFormat
TingEventArgs
E) { DataGridView dgv = (DataGridView)sender; // 如果单元格是“
column1”列的单元格 if (dgv.
columns[e.
columnIndex].Name == "
column1" && e.Value is
String)
{ // 将单元格值改为大写
String str = e.Value.To
String(
); e.Value = str.ToUpper(
); // 应用该Format,Format完毕。 e.Format
TingApplied = true; } } CellFormat
Ting事件的DataGridViewCellFormat
TingEventArgs对象的Value属性一开始保存着未被格式化的值。当Value属性被设定表示用的文本之后,把Format
TingApplied属性做为True,告知DataGridView文本已经格式化完毕。@R_737_
7724@的话,DataGridView会根据已经设定的Format,NullValue,Data
sourceNullValue,FormatProvider属性会将Value属性会被重新格式化一遍。 -------------------------------------------------------------------------------- ⑰ DataGridView 用户输入时,单元格输入
值的设定 GO TO TOP 通过 DataGridView.CellParsing 事件可以设定用户输入的值。下面的示
例:当输入英文文本内容的时候,立即被改变为大写。 [VB.NET] 'CellParsing 事件处理方法 Private Sub DataGridView1_CellParsing(ByVal sender As Ob
ject,_ ByVal e As DataGridViewCellParsingEventArgs) _ Handles DataGridView1.CellParsing Dim dgv As DataGridView = CType(sender,DataGridView) ' 单元格列为“
column1”时
if Dgv.
columns(e.
columnInde
X).Name = "
column1" AndAlso _ e.DesiredType Is GetType(
String) Then ' 将单元格值设为大写 e.Value = e.Value.To
String().ToUpper() ' 解析完毕 e.ParsingApplied = True End If End Sub [C#] //CellParsing 事件处理方法 private void DataGridView1_CellParsing(ob
ject sender,DataGridViewCellParsingEventArgs
E) { DataGridView dgv = (DataGridView)sender; //单元格列为“
column1”时 if (dgv.
columns[e.
columnIndex].Name == "
column1" && e.DesiredType == typeof(
String))
{ //将单元格值设为大写 e.Value = e.Value.To
String().ToUpper(
); //解析完毕 e.ParsingApplied = true; } } -------------------------------------------------------------------------------- ⑱ DataGridView 新加行的默认
值的设定 GO TO TOP 需要指定新加行的默认
值的时候,可以在DataGridView.
DefaultValuesNeeded事件里处理。在该事件中处理除了可以设定默认值以外,还可以指定某些特定的单元格的ReadOnly属性等。 [VB.NET] '
DefaultValuesNeeded 事件处理方法 Private Sub DataGridView1_
DefaultValuesNeeded(ByVal sender As Ob
ject,_ ByVal e As DataGridViewRowEventArgs) _ Handles DataGridView1.
DefaultValuesNeeded ' 设定单元格默认值 e.Row.Cells("
column1").Value = 0 e.Row.Cells("
column2").Value = "-" End Sub [C#] //
DefaultValuesNeeded 事件处理方法 private void DataGridView1_
DefaultValuesNeeded(ob
ject sender,DataGridViewRowEventArgs
E) { // 设定单元格的默认值 e.Row.Cells["
column1"].Value = 0; e.Row.Cells["
column2"].Value = "-"; }