Search code examples
c#asp.netcheckboxlist

Need help for insert data from multiple check-box-list into database


for (int i = 0; i < CheckBoxList3.Items.Count + 1; i++)
             {
               if (CheckBoxList3.Items[i].Selected || CheckBoxList4.Items[i].Selected || CheckBoxList5.Items[i].Selected)
                {
                    str1 += CheckBoxList3.Items[i].Text.ToString() + "," + CheckBoxList4.Items[i].Text.ToString() +"," + CheckBoxList5.Items[i].Text.ToString() + ",";

I receive the error call "Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index". How to solve this issue?

What I want to do was collect the data from checkedbox in multiple check-box-list and combine together and store it into database.

Any suggestion or help would be great. Thanks

UPDATE : This is one of my check box list. The error point to my second line of the for loop.

 <asp:CheckBoxList ID="CheckBoxList3" runat="server" RepeatDirection="Horizontal" Width="900px">
            <asp:ListItem>Chicken</asp:ListItem>
            <asp:ListItem>Tomato</asp:ListItem>
            <asp:ListItem>Garlic</asp:ListItem>
        </asp:CheckBoxList>

Solution

  • Just change your for loop like below:

    for (int i = 0; i < CheckBoxList3.Items.Count; i++)
        if (CheckBoxList3.Items[i].Selected)
            str1 += CheckBoxList3.Items[i].Text.ToString() + ",";
    
    for (int i = 0; i < CheckBoxList4.Items.Count; i++)
        if (CheckBoxList4.Items[i].Selected)
            str1 += CheckBoxList4.Items[i].Text.ToString() + ",";
    
    for (int i = 0; i < CheckBoxList5.Items.Count; i++)
        if (CheckBoxList5.Items[i].Selected)
            str1 += CheckBoxList5.Items[i].Text.ToString() + ",";
    

    UPDATE

    @Caner LENGER has a good idea. But as I mentioned in the comment of his answer it's partially true, because list.Min returns minimum value of a list that in your case it's not gonna work. Why?

    Imagine you have 3 CheckBoxLists that each one has 3 items in it except one of them that has 4. Using list.Min you'll get 3, No matter what's inside the 4th value of CheckBoxList.

    So, I changed his code and here is the tested result:

    public static string CombineCheckboxLists(params CheckBoxList[] list)
    {
        StringBuilder sb = new StringBuilder();
    
        foreach (CheckBoxList checkBoxList in list)
        {
            int counter = checkBoxList.Items.Count;
    
            for (int i = 0; i < counter; i++)
                sb.Append(checkBoxList.Items[i].Selected ? checkBoxList.Items[i].Text + "," : "");
        }
    
        return sb.ToString();
    }