2024年3月31日发(作者:)
DataGridView在vb.net中的操作技巧目录:
1、 取得或者修改当前单元格的内容
2、 设定单元格只读
3、 不显示最下面的新行
4、 判断新增行
5、 行的用户删除操作的自定义
6、 行、列的隐藏和删除
7、 禁止列或者行的Resize
8、 列宽和行高以及列头的高度和行头的宽度的自动调整
9、 冻结列或行
10、 列顺序的调整
11、 行头列头的单元格
12、 剪切板的操作
13、 单元格的ToolTip的设置
14、 右键菜单(ContextMenuStrip)的设置
15、 单元格的边框、 网格线样式的设定
16、 单元格表示值的设定
17、 用户输入时,单元格输入值的设定
18、 设定新加行的默认值
1、 DataGridView 取得或者修改当前单元格的内容:
当前单元格指的是 DataGridView 焦点所在的单元格,它可以通过 DataGridView 对象的
CurrentCell 属性取得。如果当前单元格不存在的时候,返回Nothing(C#是null)
[]
' 取得当前单元格内容 MessageBox.Show(DataGridVintCel)
' 取得当前单元格的列 Index
MessageBox.Show(DataGridVintCelnIndex)
' 取得当前单元格的行 Index
MessageBox.Show(DataGridVintCeldex)
另外,使用 DataGridVintCellAddress 属性(而不是直接访问单元格)来确定单元格
所在的行:DataGridVintCellAddress.Y 和列: DataGridVintCellAddress.X 。
这对于避免取消共享行的共享非常有用。
当前的单元格可以通过设定 DataGridView 对象的 CurrentCell 来改变。可以通过 Curre
ntCell 来设定
DataGridView 的激活单元格。将 CurrentCell 设为 Nothing(null) 可以取消激活的单元格。
[]
' 设定 (0, 0) 为当前单元格
DataGridVintCell = DataGridView1(0, 0)
--------------------------------------------------------------------------------
2、 DataGridView 设定单元格只读:
1) 使用 ReadOnly 属性
如果希望,DataGridView 内所有单元格都不可编辑, 那么只要:
[]
第 1 页 共 6 页
' 设置 DataGridView1 为只读
DataGridVinly = True
如果希望,DataGridView 内某个单元格不可编辑, 那么只要:
[]
' 设置 DataGridView1 的第2列整列单元格为只读
DataGridVins(1).ReadOnly = True
' 设置 DataGridView1 的第3行整行单元格为只读
DataGridVi(2).ReadOnly = True
' 设置 DataGridView1 的[0,0]单元格为只读
DataGridView1(0, 0).ReadOnly = True
2) 使用 EditMode 属性
DataGridViode 属性被设置为 DataGridViewEditMode.EditProgrammatically 时,用
户就不能手动编辑单元格的内容了。但是可以通过程序,调用 DataGridViEdit 方
法,使单元格进入编辑模式进行编辑。
[]
DataGridViode = DataGridViewEditMode.EditProgrammatically
3) 根据条件设定单元格的不可编辑状态
当一个一个的通过单元格坐标设定单元格 ReadOnly 属性的方法太麻烦的时候,你可以通
过 CellBeginEdit 事件来取消单元格的编辑。
[]
'CellBeginEdit 事件处理方法
Private Sub DataGridView1_CellBeginEdit(ByVal sender As Object, _
ByVal e As DataGridViewCellCancelEventArgs) _
Handles DataGridVieginEdit
Dim dgv As DataGridView = CType(sender, DataGridView)
' 是否可以进行编辑的条件检查
If ns(nIndex).Name = "Column1" AndAlso _
Not CBool(dgv("Column2", dex).Value) Then
' 取消编辑
l = True
End If
End Sub
--------------------------------------------------------------------------------
3、 DataGridView 不显示最下面的新行:
通常 DataGridView 的最下面一行是用户新追加的行(行头显示 * )。如果不想让用户新
追加行即不想显示该新行,可以将 DataGridView 对象的 AllowUserToAddRows 属性设置
为 False。
[]
' 设置用户不能手动给 DataGridView1 添加新行
DataGridViUserToAddRows = False
补足: 如果 DataGridView 的 DataSource 绑定的是 DataView, 还可以通过设置 DataV
Add
属性为 False 来达到同样的效果。
--------------------------------------------------------------------------------
第 2 页 共 6 页


发布评论