ExtensionMethod.NET Home of 880 C#, Visual Basic, F# and Javascript extension methods

CheckedList<T>

Provides a generic method to retrieve checked items in a CheckedListBox where the CheckedListBox has been loaded with a list of T. In the example provided a record is used while in another case the source might be a class that represents a record from a database.

Source

public static class CheckedListBoxExtensions
{
    public static List<T> CheckedList<T>(this CheckedListBox sender)
        => sender.Items.Cast<T>()
            .Where((_, index) => sender.GetItemChecked(index))
            .Select(item => item)
            .ToList();
}

Example

public record MonthItem(int Index, string Name)
{
    public override string ToString() => Name;
}


using static System.Globalization.DateTimeFormatInfo;
public static class Common
{
    public static MonthItem[] Months => 
        CurrentInfo.MonthNames[..^1]
            .Select((monthName, index) => new MonthItem(index + 1, monthName))
            .ToArray();
}

private void SomeForm_Load(object sender, EventArgs e)
{
    MonthsCheckedListBox.Items.AddRange(Common.Months);
}

Author: Karen Payne

Submitted on: 18 mrt. 2024

Language: csharp

Type: System.Windows.Forms.CheckedListBox

Views: 825