How can I get the CheckBoxList selected values, what I have doesn't seem to work C#.NET/VisualWebPart
Asked Answered
B

6

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"));
Buonaparte answered 1/3, 2012 at 20:9 Comment(2)
this code should work.. what event do you have this code placed under also do you actually YrChkBox.Items.Count have a value..??Garaway
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?Buonaparte
S
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.

Selves answered 1/3, 2012 at 20:26 Comment(4)
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.Buonaparte
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 thoughBuonaparte
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.Selves
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 +1Buonaparte
G
5

Try something like this:

foreach (ListItem listItem in YrChkBox.Items)
{
    if (listItem.Selected)
    { 
       //do some work 
    }
    else 
    { 
      //do something else 
    }
}
Garaway answered 1/3, 2012 at 20:22 Comment(2)
@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 +1Buonaparte
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 serversideBuonaparte
F
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);
Fungal answered 10/12, 2013 at 9:11 Comment(0)
S
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());
Scab answered 6/6, 2016 at 12:8 Comment(0)
M
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();
Mystic answered 29/5, 2014 at 5:50 Comment(0)
W
-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;
            }
        }
    }
}
Wallet answered 21/7, 2014 at 9:14 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.