13

I am creating a CheckBoxList in a class file and am using an HTMLTextWriter to render the control.

I'm using the following code to store the selected values in a string:

string YrStr = "";
for (int i = 0; i < YrChkBox.Items.Count; i++)
{
    if (YrChkBox.Items[i].Selected)
    {
        YrStr += YrChkBox.Items[i].Value + ";"; 
    }
}

I stepped through the code and it doesn't seem to hit the inside of the if statement & the selected value attribute is false every time ... Anyone have an idea of how I can address this?

I populate it using the following:

 YrChkBox.Items.Add(new ListItem("Item 1", "Item1"));
Suhaib Janjua
  • 3,538
  • 16
  • 59
  • 73
anpatel
  • 1,952
  • 4
  • 19
  • 36
  • this code should work.. what event do you have this code placed under also do you actually YrChkBox.Items.Count have a value..?? – MethodMan Mar 01 '12 at 20:18
  • OnClick; the answer to the if statement always seems to be false. This is in a Class file though, would PostBacks have anything to do with this? – anpatel Mar 01 '12 at 20:22

6 Answers6

28

In your ASPX page you've got the list like this:

    <asp:CheckBoxList ID="YrChkBox" runat="server" 
        onselectedindexchanged="YrChkBox_SelectedIndexChanged"></asp:CheckBoxList>
    <asp:Button ID="button" runat="server" Text="Submit" />

In your code behind aspx.cs page, you have this:

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            // Populate the CheckBoxList items only when it's not a postback.
            YrChkBox.Items.Add(new ListItem("Item 1", "Item1"));
            YrChkBox.Items.Add(new ListItem("Item 2", "Item2"));
        }
    }

    protected void YrChkBox_SelectedIndexChanged(object sender, EventArgs e)
    {
        // Create the list to store.
        List<String> YrStrList = new List<string>();
        // Loop through each item.
        foreach (ListItem item in YrChkBox.Items)
        {
            if (item.Selected)
            {
                // If the item is selected, add the value to the list.
                YrStrList.Add(item.Value);
            }
            else
            {
                // Item is not selected, do something else.
            }
        }
        // Join the string together using the ; delimiter.
        String YrStr = String.Join(";", YrStrList.ToArray());

        // Write to the page the value.
        Response.Write(String.Concat("Selected Items: ", YrStr));
    }

Ensure you use the if (!IsPostBack) { } condition because if you load it every page refresh, it's actually destroying the data.

Walk
  • 1,136
  • 8
  • 8
  • I do not have it in the mark up at all. I have it in a text writer. Give me a second I'll paste my code for that part. – anpatel Mar 01 '12 at 20:45
  • Ahh I see what you're saying, add the selected values to a list as they get selected... I'll try that, I'm worried about reloading the page everytime a user selects a checkbox though – anpatel Mar 01 '12 at 21:25
  • You can remove the AutoPostBack="True" part from the ASPX page, and it should behave the same way on a post back event from another event such as a button press. That was just for an example. – Walk Mar 01 '12 at 21:50
  • I can't seem to add a Server-Side control in Code-behind and add render it through HTMLTextWriter... any ideas on how I can do this. I really need to be able to retrieve the selected values of the checkbox list, thank you for your help +1 – anpatel Mar 02 '12 at 15:47
5

Try something like this:

foreach (ListItem listItem in YrChkBox.Items)
{
    if (listItem.Selected)
    { 
       //do some work 
    }
    else 
    { 
      //do something else 
    }
}
MethodMan
  • 18,625
  • 6
  • 34
  • 52
  • 1
    @Kraze Exactly what I have right now.. except I have it in a for loop, I tried it with your syntax and yes it is in fact the same thing but I like your syntax more so I'll keep it lol +1 – anpatel Mar 01 '12 at 21:29
  • 2
    Ahh I see what you're saying, yeah you're right I wasn't doing that. I really wish that helped though T_T i'm having the same issue.. I think it is because my button is not serverside – anpatel Mar 02 '12 at 15:49
3

check boxlist selected values with seperator

 string items = string.Empty;
        foreach (ListItem i in CheckBoxList1.Items)
        {
            if (i.Selected == true)
            {
                items += i.Text + ",";
            }
        }
        Response.Write("selected items"+ items);
kavitha Reddy
  • 3,303
  • 24
  • 14
3

An elegant way to implement this would be to make an extension method, like this:

public static class Extensions
{
    public static List<string> GetSelectedItems(this CheckBoxList cbl)
    {
        var result = new List<string>();

        foreach (ListItem item in cbl.Items)
            if (item.Selected)
                result.Add(item.Value);

        return result;
    }
}

I can then use something like this to compose a string will all values separated by ';':

string.Join(";", cbl.GetSelectedItems());
Fred Mauroy
  • 1,219
  • 1
  • 11
  • 10
0

// Page.aspx //

// To count checklist item

  int a = ChkMonth.Items.Count;
        int count = 0;

        for (var i = 0; i < a; i++)
        {
            if (ChkMonth.Items[i].Selected == true)
            {
                count++;
            }
        }

// Page.aspx.cs //

  // To access checkbox list item's value //
   string YrStrList = "";
        foreach (ListItem listItem in ChkMonth.Items)
        {
            if (listItem.Selected)
            {
                YrStrList = YrStrList + "'" + listItem.Value + "'" + ",";
            }

        }

        sMonthStr = YrStrList.ToString();
-1

// aspx.cs

// Load CheckBoxList selected items into ListBox

    int status = 1;
    foreach (ListItem  s in chklstStates.Items  )
    {
        if (s.Selected == true)
        {
            if (ListBox1.Items.Count == 0)
            {
                ListBox1.Items.Add(s.Text);

            }
            else
            {
                foreach (ListItem list in ListBox1.Items)
                {
                    if (list.Text == s.Text)
                    {
                        status = status * 0;

                    }
                    else
                    {
                        status = status * 1;
                    }
                }
                if (status == 0)
                { }
               else
                {
                    ListBox1.Items.Add(s.Text);
                }
                status = 1;
            }
        }
    }
}