Click here to Skip to main content
15,913,027 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
C#
private void btnaddname_Click(object sender, EventArgs e)
        {
            string connstring = "server=xyz\\sqlexpress;Database=myapp;Integrated Security=True";
            SqlConnection con = new SqlConnection(connstring);
            if (con.State == ConnectionState.Closed)
            {
                con.Open();
            }
            SqlCommand sqlCmd = new SqlCommand(@"INSERT INTO Table_Name(Name) VALUES (@name",con);
            sqlCmd.Parameters.Add("@name", SqlDbType.VarChar, 25).Value = textBoxname.Text;
            con.Close();
        }
Posted
Updated 11-Dec-13 1:53am
v2

Try like this..



C#
string connstring = "server=xyz\\sqlexpress;Database=myapp;Integrated Security=True";
            SqlConnection con = new SqlConnection(connstring);            
                con.Open();             

            SqlCommand sqlCmd = new SqlCommand(@"INSERT INTO Table_Name(Name) VALUES ('" + textBoxname.Text +  "')");
            sqlCmd.Connection = con;
         
            sqlCmd.ExecuteNonQuery();
            con.Close();
 
Share this answer
 
Comments
uditCsharp 11-Dec-13 8:00am    
thank you.. that was simple and effective.
Karthik_Mahalingam 11-Dec-13 8:03am    
:) Thank u..
uditCsharp 11-Dec-13 8:03am    
and i also found out what i was missing..
Karthik_Mahalingam 11-Dec-13 8:03am    
its good to learn from mistakes :)
0) Your query is incorrect, you didn't close that properly(missing closing parenthesis at end)
C#
SqlCommand sqlCmd = new SqlCommand(@"INSERT INTO Table_Name(Name) VALUES (@name)",con);

1) You forgot to execute, below line is missing.
C#
sqlCmd.ExecuteNonQuery();

2) Don't use hard-code connectionstrings. Get those details from config files. Check the below one for sample
How to get Connection String from App.Config in C#[^]
3) Don't use Reserved keywords for columns. Use meaningful column names like Emp_Name(instead of Name)
Check it out for more details. Reserved Keywords[^]
4) Learn more before use things.
 
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