DataGridView添加按钮功能示例(VB.NET)
想在你的DataGridView
中加个按钮?其实挺。只要在合适的地方动态添加一个按钮,就能实现你想要的交互效果了。比如,你可以在供应商编码列旁边放一个按钮,点击后弹出一个窗体,一些操作。
步骤也不复杂。,你要通过监听CellEnter
事件来清空控件,创建一个按钮,设置按钮的属性(像字体、大小、位置),添加一个点击事件。这时,按钮就会出现在指定单元格里,等你点击后做进一步的。
注意,按钮添加到DataGridView
后,要确保事件的程序绑定正确,才能响应点击。下面是代码示例:
Private Sub DataGridView1_CellEnter(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView1.CellEnter
Me.DataGridView1.Controls.Clear() '清除已有的控件
Dim btn As System.Windows.Forms.Button = New System.Windows.Forms.Button() '创建一个新的按钮
If (e.ColumnIndex.Equals(Me.DataGridView1.Columns("itemcode").Index)) Then '如果当前进入的是供应商编码列
btn.Text = "" '设置按钮文本
btn.Font = New System.Drawing.Font("Arial", 7) '设置字体
btn.Visible = True '设置按钮可见
btn.Width = Me.DataGridView1.GetCellDisplayRectangle(e.ColumnIndex, e.RowIndex, True).Height '设置按钮宽度
btn.Height = Me.DataGridView1.GetCellDisplayRectangle(e.ColumnIndex, e.RowIndex, True).Height '设置按钮高度
AddHandler btn.Click, AddressOf btn_click '添加点击事件程序
Me.DataGridView1.Controls.Add(btn) '将按钮添加到 DataGridView 中
btn.Location = New System.Drawing.Point(
Me.DataGridView1.GetCellDisplayRectangle(e.ColumnIndex, e.RowIndex, True).Right - btn.Width, _
Me.DataGridView1.GetCellDisplayRectangle(e.ColumnIndex, e.RowIndex, True).Y) '设置按钮的位置
End If
End Sub
想要实现按钮点击后的功能,可以通过绑定事件来。比如,可以打开一个新的窗体:
Private Sub btn_click(ByVal sender As Object, ByVal e As EventArgs)
Dim f As Form = New Form() '创建一个新的窗体
f.ShowDialog(Me.DataGridView1) '显示窗体为模态对话框
End Sub
挺简单吧?如果你需要在DataGridView
中按钮交互,这个方法适用。
1.48KB
文件大小:
评论区