給DataGrid加上右鍵菜單

來源:互聯網
上載者:User
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



相關文章

E-Commerce Solutions

Leverage the same tools powering the Alibaba Ecosystem

Learn more >

Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

Learn more >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。