CSDN博客

img 2066

给DataGrid加上右键菜单

发表于2004/4/27 23:54:00  950人阅读

分类: .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日

我的QQ:  26624998
我的网站:
http://blog.csdn.net/2066/

0 0

相关博文

我的热门文章

img
取 消
img