Monday, May 5, 2014

Get check status of a CheckedListBox item using text instead of index (Extension Method)

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
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
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

C#.NET
Code:
 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
1
2
3
4
5
6
7
8
9
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

C#
Code:
   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");
            }

0 comments:

Post a Comment