Click here to Skip to main content
15,902,112 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
am trying to save data from checkedlist box into a db. the first checked box gets save but the subsequent checked list item generates the error.

incorrect syntax near 's'
unclosed quotation mark after the character string')'

please help me out

C#
private void btnSave_Click(object sender, EventArgs e)
{
   
    SqlConnection conn = new SqlConnection(ConfigurationSettings.AppSettings["ConnectionString"]);
    conn.ConnectionString = "Data Source=USER-PC;Initial Catalog=PIWCDB;User ID=sa;Password=mike";

    string StrQuery;

    foreach (var checkedItem in this.cblMinistries.CheckedItems)
    {
        SqlCommand comm = new SqlCommand();
        comm.Connection = conn;

        StrQuery = @"INSERT INTO tblTry VALUES ('" + this.txtID.Text + "', '" + checkedItem + "')";
        
        comm.CommandText = StrQuery;
        conn.Open();
        comm.ExecuteNonQuery();
        conn.Close();
    }
    MessageBox.Show("Record was successfully Added");
}
Posted
Updated 14-Apr-14 22:54pm
v3
Comments
Richard MacCutchan 15-Apr-14 4:57am    
I'm not sure what type checkedItem is, but maybe that is the problem. However, you would be much better using proper parameterised queries for your SQL commands; if nothing else it protects against SQL injection attacks.
Herman<T>.Instance 15-Apr-14 5:06am    
checkItem will have a Value or something that is needed.
Richard MacCutchan 15-Apr-14 5:16am    
"a Value or something that is needed"
And in technical terms that means what?
Herman<T>.Instance 15-Apr-14 7:57am    
that you should add a point after checkedItem and see which other properties are available.
Richard MacCutchan 15-Apr-14 15:57pm    
What?

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