给DataGrid加上右键菜单
2024-07-21 02:23:35
供稿:网友
代码如下:
dim filename as string
dim myxmldataset as new dataset
filename = "sunhai.xml"
myxmldataset.readxml(filename)
form1.definstance.datagrid1.datasource = myxmldataset
启动程序,datatable默认是闭合的,需要手动点击展开,不胜其烦,用如下代码实现自动展开datatable:
private sub form1_load(byval sender as object, byval e as system.eventargs) handles mybase.load
datagrid1.expand(-1) '要展开的行数,设为-1表示展开所有行
datagrid1.navigateto(0, "datatablename")
end sub
获得在datagrid1鼠标右击的座标
dim rownum, columnnum as integer '分别是行号和列号
private sub datagrid1_mousedown(byval sender as object, byval e as system.windows.forms.mouseeventargs) handles datagrid1.mousedown
dim mygrid as datagrid = ctype(sender, datagrid)
dim hti as system.windows.forms.datagrid.hittestinfo
hti = mygrid.hittest(e.x, e.y)
if e.button = mousebuttons.right and e.clicks = 1 then '如果是鼠标右击
select case hti.type '
case system.windows.forms.datagrid.hittesttype.cell, system.windows.forms.datagrid.hittesttype.rowheader, system.windows.forms.datagrid.hittesttype.columnheader
rownum = hti.row '获得鼠标右击所在行
columnnum = hti.column '获得鼠标右击所在列
end select
end if
end sub
添加contextmenu
在设计模式添加contextmenu1:
text name
删除一行 mnudeleterow
插入一行 mnuinsertrow
把datagrid1属性中的contextmenu设为contextmenu1。
private sub mnudeleterow_click(byval sender as system.object, byval e as system.eventargs) handles mnudeleterow.click
myxmldataset.tables(0).rows.removeat(rownum) '删除行
end sub
private sub mnuinsertrow_click(byval sender as system.object, byval e as system.eventargs) handles mnuinsertrow.click
dim row1 as datarow = myxmldataset.tables(0).newrow
myxmldataset.tables(0).rows.insertat(row1, rownum)
myxmldataset.acceptchanges() '不加这句,你会发现所插入行都到“最后”了
end sub