First, realize that the CheckedListbox is kind of an old fossil Control that does not offer the binding goodness of newer controls: [
^]. You may find that setting the DataSource of a CheckedListbox in a standard way suddenly throws errors: [
^]
You need to use AddRange to set the Items in the CheckedListbox: AddRange requires ab Array of Object. Example:
dictStrToInt = new Dictionary<string, int>()
{
{ "M", 5 },
{ "Tu", 10 },
{ "W", 15 },
{"Th", 20 },
{ "F", 25 }
};
checkedListBox1.Items.AddRange(dictStrToInt.Keys.ToArray());
Now we can get the total of all checked itms;
private void checkedListBox1_SelectedValueChanged(object sender, EventArgs e)
{
var chkditems = checkedListBox1.CheckedItems.Cast<string>();
int total = chkditems.Sum(cki => dictStrToInt[cki]);
Console.WriteLine(total);
}
And, how would this be different from using an Enum ?
checkedListBox1.Items.AddRange(Enum.GetNames(typeof(WkHrs)));
private void checkedListBox1_SelectedValueChanged(object sender, EventArgs e)
{
var chkditems = checkedListBox1.CheckedItems.Cast<string>();
int total = chkditems.Sum(cki => (int)Enum.Parse(typeof(WkHrs), cki));
Console.WriteLine(total);
}
imho, using an Enum is more complex because of the necessary casting, and parsing (in bold, above). While I'm not 100% certain, I bet reflection is involved, and, I believe that is to be avoided.
Questions ?