2014-07-09 60 views
1

我正在使用DatagridView工具。在這裏,我正在對列進行手動輸入並將其直接保存到數據庫中。我有5個列,其中3個是字母數字,2個是數字列。如何使用VB.Net在datagridview的特定列中設置單元格格式?

我已經將條件設置爲在EditingControlShowing事件中使用處理程序的數字列。

If grdLedgerDetails.CurrentCell.ColumnIndex = 4 Then 
     AddHandler CType(e.Control, TextBox).KeyPress, AddressOf TextBox_keyPress 
    ElseIf grdLedgerDetails.CurrentCell.ColumnIndex = 5 Then 
     AddHandler CType(e.Control, TextBox).KeyPress, AddressOf TextBox_keyPress 
    End If 


Private Sub TextBox_keyPress(ByVal sender As Object, ByVal e As KeyPressEventArgs) 
    If Char.IsDigit(CChar(CStr(e.KeyChar))) = False Then e.Handled = True 
End Sub 

此條件適用。但問題是,這種情況適用於所有列。我只是想讓它在指定的列上工作。

請幫我解決這個問題。

在此先感謝。

回答

1

這工作得很好。

Private Sub grdLedgerDetails_EditingControlShowing(sender As Object, e As     System.Windows.Forms.DataGridViewEditingControlShowingEventArgs) Handles grdLedgerDetails.EditingControlShowing 
    Select grdLedgerDetails.CurrentCell.ColumnIndex 
     Case 2, 3 
      RemoveHandler CType(e.Control, TextBox).KeyPress, AddressOf TextBox_keyPress 
     Case 4, 5 
      AddHandler CType(e.Control, TextBox).KeyPress, AddressOf TextBox_keyPress 
    End Select 
End Sub 



Private Sub TextBox_keyPress(ByVal sender As Object, ByVal e As KeyPressEventArgs) 
    If Not Char.IsControl(e.KeyChar) And Not Char.IsDigit(e.KeyChar) And e.KeyChar <> "." Then 
     e.Handled = True 
    End If 
     End Sub 
+0

是的,它的工作很好 – Shell

0

嘗試這樣

Private Sub dgv_EditingControlShowing(ByVal sender As Object, ByVal e As DataGridViewEditingControlShowingEventArgs) 
    RemoveHandler CType(e.Control, TextBox).KeyPress, AddressOf TextBox_keyPress 
    AddHandler CType(e.Control, TextBox).KeyPress, AddressOf TextBox_keyPress 
End Sub 

Private Sub TextBox_keyPress(ByVal sender As Object, ByVal e As KeyPressEventArgs) 
    Select Case grdLedgerDetails.CurrentCell.ColumnIndex 
     Case 4,5 
      If Char.IsDigit(CChar(CStr(e.KeyChar))) = False Then e.Handled = True 
    End Select 
End Sub 
+0

對不起,問題是..當我第一次輸入字母數字列時,它工作正常。但是,一旦我在數字列中進行更改並嘗試在字母數字列中進行編輯,它將採用數字列的格式並且不允許鍵入字符。有關這個問題的任何想法? – charu

+0

@charu你嘗試過'e.ColumnIndex'而不是'CurrentCell.ColumnIndex'嗎? – Shell

+0

但e.columnindex不會在控件事件中工作。 – charu

相關問題