Donate

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
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
 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);
        }
    }
And below codes are how to use these extension methods.
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
C#.NET
   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

Donate

Popular Posts From This Blog

WPF CRUD Application Using DataGrid, MVVM Pattern, Entity Framework, And C#.NET

TypeScript Error Or Bug: The term 'tsc' is not recognized as the name of a cmdlet, function, script file, or operable program.

Invalid nested tag div found, expected closing tag input