Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CheckboxList Display All Selected Boxes

I submit the form and receive an email that states the results of the form, in this case it will be if any of the three checkboxes have been selected. My current issue is that it won't display that the second or third checkbox is selected if more then one checkbox is selected.

Example: I check all three checkboxes my result is:

  • Marketing Mailings: Yes
  • 3rd Party Mailings: No
  • VISA Promotions: No

When should display as all of them saying Yes like this:

  • Marketing Mailings: Yes
  • 3rd Party Mailings: Yes
  • VISA Promotions: Yes

My front page code:

<td class="nobor">
        <asp:CheckBoxList ID="OptList" runat="server">
        </asp:CheckBoxList>

My Page Load:

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            OptList.Items.Add(new ListItem("Marketing Mailings", "1"));
            OptList.Items.Add(new ListItem("3rd Party Mailings", "2"));
            OptList.Items.Add(new ListItem("VISA Promotions", "3"));
        }

Within my Submit_Click where the body of the email is created:

sb.Append("<u>Opt-Out Preference</u><br/>");

if (OptList.SelectedItem.Value == "1") sb.Append("<b>Marketing Mailings:</b>&nbsp;Yes<br />");
else sb.Append("<b>Marketing Mailings:</b>&nbsp;No<br />");

if (OptList.SelectedItem.Value == "2") sb.Append("<b>3rd Party Mailings:</b>&nbsp;Yes<br />");
else sb.Append("<b>3rd Party Mailings:</b>&nbsp;No<br />");

if (OptList.SelectedItem.Value == "3") sb.Append("<b>VISA Promotions:</b>&nbsp;Yes<br />");
else sb.Append("<b>VISA Promotions:</b>&nbsp;No<br />");
like image 426
techora Avatar asked Mar 18 '26 04:03

techora


1 Answers

The SelectedItem will return one item, not all of them.
You should modify your code to something like this:

if (OptList.Items[0].Selected) sb.Append("<b>Marketing Mailings:</b>&nbsp;Yes<br />");
else sb.Append("<b>Marketing Mailings:</b>&nbsp;No<br />");

if (OptList.Items[1].Selected) sb.Append("<b>3rd Party Mailings:</b>&nbsp;Yes<br />");
else sb.Append("<b>3rd Party Mailings:</b>&nbsp;No<br />");

etc... Note that I'm checking each Item if it is selected instead of the SelectedItem value.

Another option is to iterate through all the items and find those which are selected:

var ListOfSelectedValues = OptList.Items.Cast<ListItem>().Where(x => x.Selected).Select(x => x.Value).ToList();

This will return a list of all values that were selected...

like image 132
Blachshma Avatar answered Mar 19 '26 18:03

Blachshma



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!