I'm using visual studio 2010 and C# and this is the Implementation of a WPF button. IT takes two textbox values and insert them into a database table. i did create a service based database and the did configure it on app.config file. Table has two columns, product id(int) and product name(varchar). But when i run this code it doesn't give any errors. when i enter two values and press that button it shows that message box saying "Data Entered Successfully". but when I open the database on vs 2010 it just keeps null values. So the problem is that values are not inserted into the table even though i get the message "Data Entered Successfully"

private void button1_Click(object sender, RoutedEventArgs e)

          SqlConnection con = new SqlConnection();  // ‘con’ is assigned as a object of SqlConnection

            con.ConnectionString = ConfigurationManager.ConnectionStrings["biyonsaPhaConnectionString"].ConnectionString;

            // Connection String defined in ‘app.config’ was assigned to object        

            con.Open(); // connection is opened.
            string que = "insert into products values('" + textBox1.Text + "','" + textBox2.Text + "')";
            SqlCommand cmd = new SqlCommand(que, con);

            cmd.ExecuteNonQuery();   // SqlCommand is executed

            MessageBox.Show("Data Entered Successfully"); //Show message box

        catch (Exception ex)



this is my app.config file

<?xml version="1.0" encoding="utf-8"?>
        <add name="biyonsaPhaConnectionString" connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\biyonsaPha.mdf;Integrated Security=True;User Instance=True" providerName="System.Data.SqlClient" />
    <add name="biyonsaPhaEntities" connectionString="metadata=res://*/biyo.csdl|res://*/biyo.ssdl|res://*/biyo.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=.\SQLEXPRESS;attachdbfilename=|DataDirectory|\biyonsaPha.mdf;integrated security=True;user instance=True;multipleactiveresultsets=True;App=EntityFramework&quot;" providerName="System.Data.EntityClient" /></connectionStrings>

Recommended Answers

All 2 Replies

ProductId is an int but you're passing it a string.

Also, you should list the columns you're inserting for:
insert into products (ProductId, Name) values(12, 'Product 12')

Additionally, you should use parameters. Not doing so can lead to SQL injection attacks. (Don't fall for the "it's only used internally" argument either. No-one is exempt from sabotage and espionage)


You cant test the execute this way:
int a = cmd.ExecuteNonQuery();
the variable can´t have value 0, if you have that value the query dondt execute in sql server.
Do you undertand me? if not i stay here.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.