DataGridViewComboBoxColumn
のほうがすっきりするような気はしますが、別解として値を管理するためのクラスを用意する方法です。
まず、「0が"なし"/1が"あり"」というのを管理するためのクラス MyType
を用意します。
(名前は別に MyType
でなくても構いませんが)
このクラスには、以下のものを実装します。
値の候補を定義する列挙型 Options
値そのもののためのプロパティ Value
メソッド ToString()
のオーバーライド
文字列から MyType
に変換するためのメソッド Parse
vb.net
1 Public Class MyType
2
3 Public Enum Options
4 なし = 0
5 あり = 1
6 End Enum
7
8 Private _Value As Integer
9 Public Property Value As Object
10 Get
11 Return _Value
12 End Get
13 Set ( value As Object )
14 If value = Nothing Then Return
15 If TypeOf value Is Integer Then
16 _Value = CType ( value , Integer )
17 ElseIf TypeOf value Is String Then
18 Integer . TryParse ( CType ( value , String ) , _Value )
19 Else
20 Integer . TryParse ( value . ToString ( ) , _Value )
21 End If
22 If _Value < > Options . なし Then
23 _Value = Options . あり
24 End If
25 End Set
26 End Property
27
28 Public Overrides Function ToString ( ) As String
29 If _Value = Options . なし Then
30 Return Options . なし . ToString ( )
31 Else
32 Return Options . あり . ToString ( )
33 End If
34 End Function
35
36 Public Shared Function Parse ( input As String ) As MyType
37 Dim instance = New MyType ( )
38 Dim v As Integer
39 If Integer . TryParse ( input , v ) Then
40 instance . Value = v
41 Else
42 If input = Options . なし . ToString ( ) Then
43 instance . Value = Options . なし
44 Else
45 instance . Value = Options . あり
46 End If
47 End If
48 Return instance
49 End Function
50
51 End Class
次に、フォーム上の DataGridView
に対して以下のように修正します。
列の ValueType
を MyType
にする
DataGridView
の EditingControlShowing
イベントを適宜処理する
vb.net
1 ' Form1 に DataGridView1 があり、そこに列 Column1 があるものと想定しています。
2 ' 名称が異なる場合は適宜読み替えてください。
3
4 Public Class Form1
5
6 Public Sub New ( )
7 ' この呼び出しはデザイナーで必要です。
8 InitializeComponent ( )
9
10 ' InitializeComponent() 呼び出しの後で初期化を追加します。
11 ' 1. 列の `ValueType` を `MyType` にする
12 Column1 . ValueType = GetType ( MyType )
13 End Sub
14
15 ' 2. `DataGridView` の `EditingControlShowing` イベントを適宜処理する
16 Private Sub DataGridView1_EditingControlShowing ( sender As Object , e As DataGridViewEditingControlShowingEventArgs ) Handles DataGridView1 . EditingControlShowing
17 Dim editingTextBox As TextBox = Nothing
18 If TypeOf e . Control Is TextBox Then
19 editingTextBox = CType ( e . Control , TextBox )
20 End If
21 If editingTextBox IsNot Nothing AndAlso DataGridView1 . CurrentCell . OwningColumn Is Column1 Then
22 ' 現在のセルの値をもとに、EditingControlに適切な文字列をセットする
23 Dim currentCellText = DataGridView1 . CurrentCell . Value ? . ToString ( )
24 If String . IsNullOrEmpty ( currentCellText ) Then
25 editingTextBox . Text = String . Empty
26 ElseIf currentCellText = MyType . Options . なし . ToString ( ) Then
27 editingTextBox . Text = CType ( MyType . Options . なし , Integer ) . ToString ( )
28 Else
29 editingTextBox . Text = CType ( MyType . Options . あり , Integer ) . ToString ( )
30 End If
31 End If
32 End Sub
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2017/08/23 10:02 編集
2017/08/24 00:32
2017/08/27 22:59