[ Download Code ]
My first stab at this, keeping things as simple as possible, was just to do it on a web form without the added complication of creating a custom control. I'm storing the resulting selection in a database as in integer bitmask, where Sunday is 1 and Saturday is 64 (so values between 0000000 and 1111111 binary or 0 and 127 decimal are allowed). To do this, all that's required is a simple CheckBoxList, with everything declared declaratively:
<asp:CheckBoxList ID="CheckBoxList1" Runat="server">
<asp:ListItem Value="1">Sunday</asp:ListItem>
<asp:ListItem Value="2">Monday</asp:ListItem>
<asp:ListItem Value="4">Tuesday</asp:ListItem>
<asp:ListItem Value="8">Wednesday</asp:ListItem>
<asp:ListItem Value="16">Thursday</asp:ListItem>
<asp:ListItem Value="32">Friday</asp:ListItem>
<asp:ListItem Value="64">Saturday</asp:ListItem>
</asp:CheckBoxList>
<asp:Button ID="Button1" Runat="server" Text="Button" OnClick="Button1_Click" />
<br />
<asp:Label ID="Label1" Runat="server"></asp:Label>
Combine that with a bit of code to extract the bitmask and display it:
int DaysOfWeekBitMask = 0;
void Button1_Click(object sender, EventArgs e)
{
Label1.Text = "";
foreach (ListItem item in CheckBoxList1.Items)
{
if (item.Selected)
{
DaysOfWeekBitMask += Int32.Parse(item.Value);
Label1.Text += item.Text + ", ";
}
}
Label1.Text += "Bitmask: " + DaysOfWeekBitMask + " (" +
System.Convert.ToString(DaysOfWeekBitMask, 2).PadLeft(7, '0') + ")";
}
The result will look something like this:
Simple. However, I intend to use this functionality on several different pages, and potentially in different applications, so I want to make it a custom control so that I can just drag and drop it wherever I need it. We'll look at how to do that next, with just a bare-bones simple example.
In a later article, I hope to take this a step further and make the control more flexible, so that a variety of listing options are supported (e.g. single vs. multi select using dropdown, ListBox, RadioButtonList, or CheckBoxList display modes). For now, I'm simply extending the CheckBoxList, as you'll see on the next page.