Click here to Skip to main content
15,890,897 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I have two checkboxlists CandidateName and Payment, and a dropdownlist. User can do multiple selections in checkboxlists and one selection at dropdownlist. I am populating those data of chechboxlists and dropdownlist to Panel nested inside UpdatePanel which has gridview and this panel. When I click on Add Button to open up Panel, all data is populating. When I tried to save selected checkedbox lists through "for loop", it is not working. When I debug at for loop statement, it is not going inside the loop. How can I have loop working so that it will save in database. Please help me advise. Thank
This is my C# code.
C#
protected void btnAddNew_Click(object sender, EventArgs e)
    {
        try
        {
      
            string strcbl1 = string.Empty;
            string strcbl2 = string.Empty;
           
            compCon = new SqlConnection(strConnectionString);
            compCon.Open();
           

            for (int i = 0; i < cblCandidateName1.Items.Count-1; i++)
            {
                if (cblCandidateName1.Items[i].Selected ==true)
                {
                    strcbl1 = strcbl1 + cblCandidateName1.Items[i].Value.ToString() + ",";
                }
            }

            for (int j = 0; j < cblPayment1.Items.Count - 1; j++)
            {
                if (cblPayment1.Items[j].Selected == true)
                {
                    strcbl2 += cblPayment1.Items[j].Value.ToString() + ",";
                }
            }
string strCourseID = ddlCourseName.Item.SelectedItem.Value.ToString();

           
            string InsertSchedule = "INSERT INTO ScheduleEmail(CANDIDATE_ID, PAYMENT_ID, TEMPLATE_ID)VALUES(@strCID, @strPID, @strCourseID)";
            SqlCommand InsertScheduleCommand = new SqlCommand(InsertSchedule, compCon);
            InsertScheduleCommand.Connection = compCon;

          
            InsertScheduleCommand.Parameters.AddWithValue(@"strCID", strcbl1);
            InsertScheduleCommand.Parameters.AddWithValue(@"strPID", strcbl2);
            InsertScheduleCommand.Parameters.AddWithValue(@"strCourseID", strCourseID);

            InsertScheduleCommand.ExecuteNonQuery();
            compCon.Close();
        }
        catch (Exception ex)
        {
            ShowPopUpMsg("Data is failed to save in table. Please contact your system administrator \n" + ex.ToString());
        }
        finally
        { 
        DispalyGridViewScheduleEmail();
        
        compCon.Close();
        }

    }


This is my html code.
ASP.NET
<asp:Panel ID="panelAddNewTitle" runat="server" style="cursor:move;font-family:Tahoma;padding:2px;" HorizontalAlign="Center" BackColor="Blue" ForeColor="White" Height="25" >Add New</asp:Panel><ajaxToolkit:ModalPopupExtender ID="mpe1"  runat="server" TargetControlID="btnAddNew1" PopupControlID="panelAddNew" RepositionMode="RepositionOnWindowResizeAndScroll" DropShadow="true" PopupDragHandleControlID="panelAddNewTitle" BackgroundCssClass="modalBackground"  ></ajaxToolkit:ModalPopupExtender>
      <asp:CheckBoxList ID="cblCandidateName1" runat="server" RepeatColumns="3" RepeatDirection="Horizontal" RepeatLayout="table">   
 <asp:CheckBoxList ID="cblPayment1" runat="server" RepeatDirection="Horizontal" RepeatLayout="Table"></asp:CheckBoxList>
<asp:DropDownList ID="ddlCourseName" runat="server"> 


<asp:Button ID="btnAddNew2" runat="server" Width="70" Text="Add" OnClick="btnAddNew_Click"  ValidationGroup="add"/>
                 
                
                <asp:Button ID="btnCancel1" runat="server" Width="70" Text="Cancel" CausesValidation="false" OnClick="Cancel_Click" ValidationGroup="add"/>
            </div>
        </asp:Panel>        
Posted

Not sure why you are why you stop one item short of the list count.

You should replace this code
C#
for (int i = 0; i < cblCandidateName1.Items.Count-1; i++)
{
    if (cblCandidateName1.Items[i].Selected ==true)
    {
        strcbl1 = strcbl1 + cblCandidateName1.Items[i].Value.ToString() + ",";
    }
}

with
C#
foreach (object checkedItem in cblCandidateName1.CheckedItems)
{
    strcbl1 += String.Format("{0},", checkedItem.ToString());
}


You should probably also trim the string before adding it to the database
C#
InsertScheduleCommand.Parameters.AddWithValue(@"strCID", strcbl1.TrimEnd(','));


That said, it is a pretty bad design to add comma separated string to a column to a database. You would probably be better of if you normalized your database.
In such a case, each item in the listbox would correspond to one row in a separate table.

Wikipedia: Database normalization[^]
Database Normalization Basics[^]
3 Normal Forms Database Tutorial[^]
 
Share this answer
 
Insted of loop Use this code . . .this one is liter then loop..

var selectedValues = checkedItem.Items.Cast<listitem>()
                          .Where(li => li.Selected)
                          .Select(li => li.Value)
                          .ToArray();</listitem>
 
Share this answer
 
I guess you are dynamically adding items to CheckBoxList from code in Page Load Event.

Have you checked IsPostBack? I guess you have not.
 
Share this answer
 
Comments
Member 10858162 28-Sep-14 2:13am    
No, I am not adding to ckhboxlist in page load event.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900