2015-05-14 63 views
0

我有一個非常標準的DataGridView和已經爲了保證整個行選擇使用獲得DataGridView中選定的行不工作VB.Net

.SelectionMode = DataGridViewSelectionMode.FullRowSelect 
.MultiSelect = False 

情況:我需要獲取選定的行,以便將行中的數據加載到另一個屏幕以「修改」數據。我正在使用以下來獲取選定的行。

Private Sub DataGridView2_CellContentClick(sender As Object, e As DataGridViewCellEventArgs) Handles DataGridView2.CellContentClick 
    Try 
     If e.RowIndex >= 0 Then 
      Dim row As DataGridViewRow 
      row = Me.DataGridView2.Rows(e.RowIndex) 
      GlobalVariables.SelectedlineItemRowNo = e.RowIndex ' Or row 
      MsgBox("GlobalVariables.SelectedlineItemRowNo is ---> " & GlobalVariables.SelectedlineItemRowNo) 

      'textboxTst.Text = row.Cells("Description").Value.ToString 
     End If 
    Catch ex As Exception 
     MsgBox(ex.Message) 
    End Try 
End Sub 

問題:問題是,大部分的時候,一個點擊上面的代碼運行時,DGV中的數據和設置e.RowIndex - 但是當我打任何空白的行上什麼也沒有發生所以導致使用前一行選擇的問題,這實際上是錯誤的行。

任何想法,將不勝感激。 在此先感謝

+0

爲什麼不處理SelectionChanged事件? –

回答

2

我想你要找的是DataGridView CellClick而不是CellContentClick。單擊單元格內容周圍的空白時,CellContentClick不會觸發。

Private Sub DataGridView2_CellClick(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView2.CellClick 
Try 
    If e.RowIndex >= 0 Then 
     Dim row As DataGridViewRow 
     row = Me.DataGridView2.Rows(e.RowIndex) 
     GlobalVariables.SelectedlineItemRowNo = e.RowIndex ' Or row 
     MsgBox("GlobalVariables.SelectedlineItemRowNo is ---> " & GlobalVariables.SelectedlineItemRowNo) 

     'textboxTst.Text = row.Cells("Description").Value.ToString 
    End If 
Catch ex As Exception 
    MsgBox(ex.Message) 
End Try 
End Sub 
0

你的問題是關於你正在使用的事件:CellContentClick。代替它,請使用:SelectionChanged。這對你的目的會更有用。

SelectionChanged

在這種情況下,e不再是一個細胞,所以你可以改變這個訪問發件人:yourListviewName.SelectedRows,,讓您與所選行的Collection

由於您已禁用multiselect屬性,因此只需訪問它的第一項。

+0

我不確定這是否有效。我試過私人小組DataGridView2_SelectionChanged(發件人爲對象,e爲DataGridViewCellEventArgs)處理DataGridView2.SelectionChanged,這並沒有工作 – mond007

+1

你是否手動編寫它?因爲這條'DataGridViewCellEventArgs'對我來說似乎很奇怪。通過選擇VS中代碼視圖頂部的事件來創建它。 –

+1

@ mond007如果您手動編寫事件句柄,請確保方法簽名與事件代理相匹配。在這種情況下,SelectionChanged是[EventHandler](https://msdn.microsoft.com/en-us/library/system.eventhandler%28v=vs.110%29.aspx)委託:'(sender As Object,e作爲EventArgs)' –