无标题文档
给DataGrid加上右键菜单
作者:Tuenhai.com MSN: king#tuenhai.com
版权声明:可以任意转载,转载时请务必以超链接形式标明文章原始出处和作者信息及本声明
开发工具:Microsoft Visual Studio .NET 2003
操作系统:Windows XP
用XML作为DataGrid的数据源
代码如下:
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
怎么在DataTable中插入列呢?tuenhai请各位指教!
2004年4月27日
Tuenhai简介:Tuenhai同学对儒释道医卜命相有一定研究,对网络及英语最感兴趣,于哲学最有心得.常人利已,圣人利他,我非圣人,取道中庸.希望与各位精英交流,MSN:king#tuenhai.com
我的网站: http://www.Tuenhai.com/