给DataGrid加上右键菜单

2066(原作) 关键字 vs.net,vb.net,xml,Microsoft Visual Studio .NET,DataGrid,弹出菜单

屠恩海(SunHai)
开发工具: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中插入列呢?请各位指教!
2004年4月27日



对该文的评论 人气:63

zjh135 (2004-4-28 8:57:55)

DATAGRID控件会淘汰掉的,功能不强!!没有PB的表格控件好

largeking (2004-4-28 1:26:02)

不知为什么我的DataGrid下面找不到HitTextInfo这个类啊!!那个高手知道为什么啊!!

Contributors: FHL