CheckedListBox中的项目是否有标记?或类似的东西?我希望能够存储与我正在显示的项目相关联的ID。
答案 0 :(得分:7)
您不需要Tag属性。控件接受任何对象,这意味着您不必只在其中放置字符串。创建一个具有字符串(和覆盖ToString()
)的类以及您需要的任何其他数据成员。
Public Class Form1
Protected Overrides Sub OnLoad(ByVal e As System.EventArgs)
MyBase.OnLoad(e)
CheckedListBox1.Items.Add(New MyListBoxItem() With {.Name = "One", .ExtraData = "extra 1"})
CheckedListBox1.Items.Add(New MyListBoxItem() With {.Name = "Two", .ExtraData = "extra 2"})
End Sub
Private Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button1.Click
For Each obj As Object In CheckedListBox1.CheckedItems
Dim item As MyListBoxItem = CType(obj, MyListBoxItem)
MessageBox.Show(String.Format("{0}/{1} is checked.", item.Name, item.ExtraData))
Next
End Sub
End Class
Public Class MyListBoxItem
Private _name As String
Private _extraData As String
Public Property Name As String
Get
Return _name
End Get
Set(ByVal value As String)
_name = value
End Set
End Property
Public Property ExtraData As String
Get
Return _extraData
End Get
Set(ByVal value As String)
_extraData = value
End Set
End Property
Public Overrides Function ToString() As String
Return Name
End Function
End Class
(被覆盖的ToString()
指示将在框中显示的内容。)
答案 1 :(得分:2)
你可以从CheckedListBox继承自己的控件并创建一个属性,在C#中就是这样,其余的功能保持不变,因此不需要进一步的代码:
public class MyCheckedListbox : System.Windows.Forms.CheckedListBox{ private object thisObj; public object Tag{ get{ return this.thisObj; } set{ this.thisObj = value; } } }
编辑:决定将VB.NET版本包含在内,也为每个人带来好处......
Public Class MyCheckedListBox Inherits System.Windows.Forms.CheckedListBox Private thisObj As Object Public Property Tag As Object Get Tag = thisObj End Get Set (objParam As Object) thisObj = objParam End Set End Property End Class
当然,这很简单,使用拳击但效果很好......
希望这有帮助
答案 2 :(得分:0)
tommieb75的翻译回答VB.NET:
Public Class MyCheckedListbox
Inherits System.Windows.Forms.CheckedListBox
Private thisObj As Object
Public Property Tag() As Object
Get
Return Me.thisObj
End Get
Set(ByVal value As Object)
Me.thisObj = value
End Set
End Property
End Class
我在www.developerfusion.com/tools
上使用翻译器