|
■No79262 (imy さん) に返信
Button1の処理は文字列を連結してしまう方法
Button2の処理は描画を独自に行う方法
文字列連結のほうが簡単ですが文字位置のずれが発生しやすくなります。
Public Class Form1
Private _ComboItems As ListComboItem
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
_ComboItems = New ListComboItem From {{"00", "北海道"}, {"01", "青森県"}}
ComboBox1.DataSource = _ComboItems
ComboBox1.ValueMember = "Value"
ComboBox1.DisplayMember = "Disp"
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
_ComboItems = New ListComboItem From {{"00", "北海道"}, {"01", "青森県"}}
ComboBox2.DataSource = _ComboItems
ComboBox2.DropDownStyle = ComboBoxStyle.DropDownList
ComboBox2.ValueMember = "Value"
ComboBox2.DisplayMember = "Disp"
ComboBox2.DrawMode = DrawMode.OwnerDrawFixed
ComboBox2.DropDownWidth = 100
End Sub
Private Sub ComboBox2_DrawItem(sender As Object, e As DrawItemEventArgs) Handles ComboBox2.DrawItem
e.DrawBackground()
Dim g = e.Graphics
If (e.State And DrawItemState.ComboBoxEdit) > 0 Then
'編集部分特有の処理
End If
Dim itm = DirectCast(ComboBox2.Items(e.Index), ComboItem)
g.DrawString(itm.Value, ComboBox2.Font, Brushes.Black, e.Bounds.Left, e.Bounds.Top)
g.DrawString(itm.Name, ComboBox2.Font, Brushes.Black, e.Bounds.Left + 20, e.Bounds.Top)
e.DrawFocusRectangle()
End Sub
End Class
Public Class ComboItem
Public Property Value As String
Public Property Name As String
Public ReadOnly Property Disp As String
Get
Return String.Format($"{Value} {Name}")
End Get
End Property
Public Overloads Function tostring()
Return Disp
End Function
End Class
Public Class ListComboItem
Inherits List(Of ComboItem)
Public Sub New()
MyBase.New()
End Sub
Public Overloads Function Add(Value As String, Name As String)
Dim ret As New ComboItem() With {.Value = Value, .Name = Name}
Me.Add(ret)
Return ret
End Function
End Class
|