プロが教えるわが家の防犯対策術!

DataGridViewにて、列ごとに入力制御を設けるために作成しました。
DataGridには、ボタンやコンボボックスの列があるため、イベントをとる
列を指定しています。



Private TextEditCtrl As DataGridViewTextBoxEditingControl 'DataGridViewのTextBoxセルを宣言

Private Sub DataGridView1_CellEnter(ByVal sender As Object, _
ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) _
Handles DataGrid.CellEnter
Dim columnIndex As Integer = Me.DataGrid.CurrentCell.ColumnIndex

Select Case Me.DataGrid.Columns(columnIndex).Name

Case "日本語" '日本語入力ONにする列
DataGrid.ImeMode = Windows.Forms.ImeMode.Hiragana

Case Else 'IME無効(半角英数のみ)
DataGrid.ImeMode = Windows.Forms.ImeMode.Disable

End Select

End Sub

Private Sub DataGrid_EditingControlShowing( _
ByVal sender As Object, _
ByVal e As System.Windows.Forms.DataGridViewEditingControlShowingEventArgs) Handles DataGrid.EditingControlShowing
Dim columnIndex As Integer = Me.DataGrid.CurrentCell.ColumnIndex

'テキストボックス列のみ適用

Select Case Me.DataGrid.Columns(columnIndex).Name

Case "日本語", "重さ", "数字", "秒"

TextEditCtrl = CType(e.Control, DataGridViewTextBoxEditingControl)
AddHandler TextEditCtrl.KeyPress, AddressOf TextEditCtrl_KeyPress

Case Else

End Select

End Sub

Private Sub TextEditCtrl_KeyPress(ByVal sender As Object, ByVal e As KeyPressEventArgs)
Dim columnIndex As Integer = Me.請求明細DataGridCommon.CurrentCell.ColumnIndex

Select Case Me.請求明細DataGridCommon.Columns(columnIndex).Name

Case "数字" '数値のみ許可

Select Case e.KeyChar

Case Chr(Keys.Back) 'BackSpace

Case Chr(Keys.D0) To Chr(Keys.D9) '数値キー

Case Else
'上記キー以外は処理しないようにする

e.Handled = True

End Select

Case "重さ" '数値とマイナスを許可

Select Case e.KeyChar

Case Chr(Keys.Back) 'BackSpace

Case Chr(Keys.D0) To Chr(Keys.D9) '数値キー

'Case Chr(Keys.NumPad0) To Chr(Keys.NumPad9)

Case "-"c

Case Else
'上記キー以外は処理しないようにする

e.Handled = True

End Select


Case "秒" '数値と小数点を許可

Select Case e.KeyChar

Case Chr(Keys.Back) 'BackSpace

Case Chr(Keys.D0) To Chr(Keys.D9) '数値キー

Case Chr(Keys.Decimal)

Case Chr(Keys.Oemcomma)

Case Chr(Keys.OemPeriod)

Case "."c

Case Else
'上記キー以外は処理しないようにする

e.Handled = True

End Select

End Select

End Sub

最後に、CellEndEditイベントにて、RemoveHandler TextEditCtrl.KeyPress, AddressOf TextEditCtrl_KeyPress、
(これもテキストボックス列のみを指定)で終わりです。

このロジックの影響か定かではないのですが、空白が入力できない行や、確定できない
コンボボックスなどが出来てしまい、困っています。
もし修正箇所ありましたら、アドバイスお願いします。

A 回答 (1件)

ハンドラを設定しているグリッドと KeyPressイベントで見ているグリッドは違っていますがこれでいいのですか?



KeyPressイベントはもう少し簡潔に書けると思いますよ
dim ss as String = 請求明細DataGridCommon.Columns(columnIndex).Name
Select Case e.KeyChar
case chr( Keys.Back )
case chr( Keys.D0 ) to chr(Keys.D9)
case "-"
  if ss<>"重さ" then
    e.handled = True
  end if
case ".",Chr(Keys.Decimal), Chr(Keys.Oemcomma), Chr(Keys.OemPeriod)
  if ss <> "秒" then
    e.handled = True
  end if
case else
  if ss<>"日本語" then
    e.handled = True
  end if
End Select

と言った具合です ・・・

私なら WithEventsでオブジェクトを宣言しておき
EditingControlShowingで オブジェクトを代入
CellEndEditで オブジェクトをNothing
オブジェクトのEnterイベントで オブジェクトのImeModeを設定
KeyPressイベントは上記の内容 と言った具合にします
    • good
    • 0

お探しのQ&Aが見つからない時は、教えて!gooで質問しましょう!