Get Check Status Of A CheckedListBox Item Using Text Instead Of Index
There was a question raised on visual basic forums if you can access an item through it's name rather than index to get it's checked status. My suggestion was to implement a custom control. However, one of the resident MVP in that forum has a better solution using extension method which is simple yet elegant. Below are the extension methods in VB.NET and C#.
VB.NET
C#.NET
And below codes are how to use these extension methods.
VB.NET
C#.NET
VB.NET
Module CheckedListBoxExtensions <Extension()> Function GetItemChecked(ByVal source As CheckedListBox, ByVal text As String) As Boolean Dim item = source.Items.Cast(Of Object)().FirstOrDefault(Function(o) source.GetItemText(o) = text) Dim index = source.Items.IndexOf(item) Return source.GetItemChecked(index) End Function End Module
public static class CheckedListBoxExtensions { public static bool GetItemChecked(this CheckedListBox source, string text) { var item = source.Items.Cast<object>().FirstOrDefault(o => source.GetItemText(o) == text); var index = source.Items.IndexOf(item); return source.GetItemChecked(index); } }
VB.NET
If (clb.GetItemChecked("US")) Then MessageBox.Show("US is checked") ElseIf (clb.GetItemChecked("AU")) Then MessageBox.Show("AU is checked") ElseIf (clb.GetItemChecked("UK")) Then MessageBox.Show("UK is checked") Else MessageBox.Show("None Selected") End If
if (clb.GetItemChecked("US")) { MessageBox.Show("US is checked"); } else if (clb.GetItemChecked("AU")) { MessageBox.Show("AU is checked"); } else if (clb.GetItemChecked("UK")) { MessageBox.Show("UK is checked"); } else { MessageBox.Show("None selected"); }
Comments
Post a Comment