Click here to Skip to main content
15,892,161 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
I am trying to send some data to a database using C#. One of the fields that gets filled out is a checkbox list. If the use selects multiple options, i would like all of them to be stored in the database. I am trying to use a stringbuilder to connect all of the options together, but I keep getting an error of not being able to convert stringbuilder to a string.

I have looked at similar questions that have been posted, but nothing I have found has corrected my problem yet so I am going to post what I have and hope someone can assist me in figuring out how to correct the problem. any and all suggestions/assistance is appreciated.

C#
protected void btnSubmitRequest_Click(object sender, EventArgs e)
    {
        string employeeName = txtEmployeeName.Text;
        string employeeNumber = txtEmployeeNum.Text;
        string contact = txtContact.Text;
        string reason = rblReason.SelectedValue;
        Boolean quickCharge;
        if (rblReason.SelectedValue != "Lost")
        {
            quickCharge = false;
        }
        else
        {
            quickCharge = Convert.ToBoolean(rblQuickCharge.SelectedValue);
        }
        string notWorkingDetails = txtNotWorkingDetails.Text;
        string newTitle = txtNewTitle.Text;
        string newLocation = txtNewLocation.Text;
        string otherDesc = txtOtherDescription.Text;
        string specialInstructions = cblSpecialInstructions.Text;
        string deliverToLoc = txtDeliverToLoc.Text;
        string deliverToDept = txtDeliverToDept.Text;

        System.Text.StringBuilder sbSpecial = new System.Text.StringBuilder();
        foreach (var str in specialInstructions)
            sbSpecial.Append(str).Append(", ");

        #region //Send to Database
        try
        {
            using (SqlConnection connection = new SqlConnection("server=10.52.2.169\\sqlcluster,1206;uid=TannerAppsWriter;pwd=TannerAppsWriter;database=TannerInternal;"))
            {
                using (SqlCommand cmdInsertRequest = new SqlCommand("HR.BadgeReplacementRequest", connection))
                {
                    cmdInsertRequest.CommandType = CommandType.StoredProcedure;

                    #region //Set Parameters to Add to StoredProcedure
                    cmdInsertRequest.Parameters.Add("@employeeName", SqlDbType.VarChar, 150);
                    cmdInsertRequest.Parameters["@employeeName"].Value = employeeName;
                    cmdInsertRequest.Parameters.Add("@employeeNumber", SqlDbType.VarChar, 50);
                    cmdInsertRequest.Parameters["@employeeNumber"].Value = employeeNumber;
                    cmdInsertRequest.Parameters.Add("@contact", SqlDbType.VarChar, 150);
                    cmdInsertRequest.Parameters["@contact"].Value = contact;
                    cmdInsertRequest.Parameters.Add("@reason", SqlDbType.VarChar, 100);
                    cmdInsertRequest.Parameters["@reason"].Value = reason;
                    cmdInsertRequest.Parameters.Add("@quickCharge", SqlDbType.Bit);
                    cmdInsertRequest.Parameters["@quickCharge"].Value = quickCharge;
                    cmdInsertRequest.Parameters.Add("@notWorkingDetails", SqlDbType.VarChar, 250);
                    cmdInsertRequest.Parameters["@notWorkingDetails"].Value = notWorkingDetails;
                    cmdInsertRequest.Parameters.Add("@newTitle", SqlDbType.VarChar, 75);
                    cmdInsertRequest.Parameters["@newTitle"].Value = newTitle;
                    cmdInsertRequest.Parameters.Add("@newLocation", SqlDbType.VarChar, 150);
                    cmdInsertRequest.Parameters["@newLocation"].Value = newLocation;
                    cmdInsertRequest.Parameters.Add("@otherDesc", SqlDbType.VarChar, 250);
                    cmdInsertRequest.Parameters["@otherDesc"].Value = otherDesc;
                    cmdInsertRequest.Parameters.Add("@specialInstructions", SqlDbType.VarChar, 50);
                    cmdInsertRequest.Parameters["@specialInstructions"].Value = sbSpecial;
                    cmdInsertRequest.Parameters.Add("@deliverToLoc", SqlDbType.VarChar, 150);
                    cmdInsertRequest.Parameters["@deliverToLoc"].Value = deliverToLoc;
                    cmdInsertRequest.Parameters.Add("@deliverToDept", SqlDbType.VarChar, 150);
                    cmdInsertRequest.Parameters["@deliverToDept"].Value = deliverToDept;

                    #endregion

                    connection.Open();

                    cmdInsertRequest.ExecuteNonQuery();
                }
            }
        }
        catch (Exception ex)
        {
            Response.Write("Error: " + ex.ToString());
        }
        #endregion
}
Posted
Updated 7-Jun-13 8:11am
v2
Comments
Richard C Bishop 7-Jun-13 14:12pm    
What line does it fail at?
Jason Milam 7-Jun-13 14:13pm    
cmdInsertRequest.ExecuteNonQuery();
Richard C Bishop 7-Jun-13 14:17pm    
You are setting "@specialInstructions" as VarChar(50), which is essentially a string with 50 characters. However, you are assiging it a stringbuilder value, which is not the same thing hence why you cannot convert one to the other.

I presume you are meaning to pass it a string that your string builder contructed?
Jason Milam 7-Jun-13 14:22pm    
ok I see what you are saying. is there a way to convert the stringbuilder value to a string so that it could be successfully converted to a VarChar?
Richard C Bishop 7-Jun-13 14:22pm    
Try sbSpecial.ToString().

Keep in mind that if the string builder exceeds the VarChar length, it will be truncated.

C#
cmdInsertRequest.Parameters["@specialInstructions"].Value = sbSpecial.ToString();


Fix this line and it should work
 
Share this answer
 
v3
Comments
Jason Milam 7-Jun-13 14:53pm    
well That definitely got me somewhere. The error is gone and information gets put in the database, but there is a problem with how it is doing it.
Here is a figurative list of items in my checkbox list:
ball - "checked"
shoe
bag - "checked"
glove
hat

Instead of putting the checked items in like this:
"ball, bag"

It is doing this
"b,a,l,l" and not putting in bag.

I give your answer 5 stars for getting the error to go away! time to fix my new problem. Thanks for your help!
Richard C Bishop 7-Jun-13 15:10pm    
Depending on what "speciealInstructions" contains as a collection, you are iterating through all of them and adding a "," after each item. The string builder is probably constructing ball in that manner.
I couldn't figure out how to get it to push each selection to the database. It just kept pushing 1 and separating the letters in it by commas as showed previously. I changed up my code and ended up doing this:

C#
CheckBoxList chkbxspecial = (CheckBoxList)form1.FindControl("cblSpecialInstructions");
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < chkbxspecial.Items.Count; i++)
        {
            if (chkbxspecial.Items[i].Selected)
            {
                sb.Append(chkbxspecial.Items[i].Value + ", ");
            }
        }
        string InputString = sb.ToString().Substring(0, sb.ToString().Length - 1);


Then did this at the stored procedure area:

C#
cmdInsertRequest.Parameters.Add("@specialInstructions", SqlDbType.VarChar, 50);
cmdInsertRequest.Parameters["@specialInstructions"].Value = InputString;


Displays great now! thanks for leading me in the right direction guys. @Allen Chong, I am still accepting your solution since it answered the original question I asked and removed the error. I just had to change things around because of the new error that arose.
 
Share this answer
 

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