2011-08-16 48 views
0

VB.NET DataGridView控件:光標細胞的datagridview vb.net中

我知道這可能是超級簡單,但我怎麼可以把閃爍的光標在窗體加載特定的細胞內?

我想要的效果就像當你有一個帶有文本框的窗體,並且當你正確設置tab鍵順序時,第一個文本框會自動擁有焦點,並且你可以立即開始輸入。

在一個相關的問題上:當你在一個單元格內時,如何讓輸入鍵激活表單的接受按鈕?

謝謝!

回答

1

說得沒錯,將輸入遊標定位到DataGridView中的特定單元格相當容易。將DataGridView的CurrentCell屬性設置爲您希望光標所在的單元格,然後調用DGV的BeginEdit方法。

這也很容易以編程方式點擊(我相信你的意思是'激活')表格的AcceptButton。呼籲表單實例的AcceptButtonPerformClick方法:

Me.AcceptButton.PerformClick() 

獲取DGV處理回車鍵是有點麻煩,即使看起來它可能不是那麼的表面上。其原因很棘手,因爲當您在編輯模式下使用DGV單元時,DGV KeyPressPreviewKeyPress事件不會觸發。解決方案是通過擴展標準DataGridView來創建自己的DataGridView,然後覆蓋ProcessCmdKey函數以觸發一個事件,該事件告訴偵聽器已按下Enter鍵。

這是你的擴展DGV控制可能是什麼樣子:

Public Class MyDataGridView 
    Inherits System.Windows.Forms.DataGridView 

    Public Event EnterKeyPressed() 

    Protected Overrides Function ProcessCmdKey(ByRef msg As System.Windows.Forms.Message, ByVal keyData As System.Windows.Forms.Keys) As Boolean 
     If keyData = Keys.Enter Then 
      RaiseEvent EnterKeyPressed() 
     End If 

     Return MyBase.ProcessCmdKey(msg, keyData) 
    End Function 
End Class 

因此,假如你使用的擴展DGV上面這裏是你怎麼做你需要做什麼:

' This positions the input cursor in the third column in the third row. 
MyDataGridView1.CurrentCell = MyDataGridView1.Rows(2).Cells(2) 
MyDataGridView1.BeginEdit(False) 


' Be sure to wire up the EnterKeyPress event on your shiny new MyDataGridView. 
Private Sub MyDataGridView1_EnterKeyPressed() Handles MyDataGridView1.EnterKeyPressed 
    Me.AcceptButton.PerformClick() 
End Sub 
+0

當我調用begin編輯方法時,雖然沒有給我一個指針...... – John

+0

@John不知道爲什麼,它適用於我。原因可能是您對DGV屬性所做的任何更改?如果您在新窗體中使用新的DGV(或「MyDataGridView」),它會起作用嗎? –

0

嘗試這段代碼肯定會起作用

dim strRowNumber as string 

For Each row As DataGridViewRow In DataGrid.Rows 

    strRowNumber = DataGrid.Rows.Count - 1 
    DataGrid.CurrentCell = DataGrid.Rows(strRowNumber).Cells(1)'Cell(1) is a cell nowhich u want to edit or set focus 
    DataGrid.BeginEdit(False) 
Next