I want to insert data into a table

Viewed 110

I'm building a C# Windows Forms database application. Data should be written in a text field and saved in a table using a button. My problem is that the data is not saved in the table.

I have built a list that should show the records of the table. When you click on the insert button, the text is displayed in the list, but it is not saved in the table.

My code:

        private void insert_Click(object sender, EventArgs e)
    {
        string con_string = Properties.Settings.Default.DB1_ConnectionString;
        SqlConnection con = new SqlConnection(con_string);
        con.Open();
        SqlCommand cmd = new SqlCommand("insert into tab_Musik values (@Titel,@Inerpret,@Genre)", con);
        cmd.Parameters.AddWithValue("@Titel", int.Parse(txt_Titel.Text));
        cmd.Parameters.AddWithValue("@Inerpret", txt_Interpret.Text);
        cmd.Parameters.AddWithValue("@Genre", double.Parse(kmb_Genre.Text));
        cmd.ExecuteNonQuery();
        con.Close();

    }

    private void show[enter image description here][1]_Click(object sender, EventArgs e)
    {
        string con_string = Properties.Settings.Default.DB1_ConnectionString;
        SqlConnection con = new SqlConnection(con_string);
        con.Open();
        SqlCommand cmd = new SqlCommand("select * from tab_Musik", con);
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        DataTable dt = new DataTable();
        da.Fill(dt);
        dataGridView1.DataSource=dt;
        
    }

enter image description here enter image description here

1 Answers

For the problem you described about clicking the insert button, the data cannot be saved to the table, you can try the following code:

private void btnAdd_Click(object sender, EventArgs e)
    {            
        string con_string = "database connection string";
        SqlConnection sqlConnection = new SqlConnection(con_string);           
        string myinsert = "insert into tab_Musik values (@Titel,@Inerpret)";
        SqlCommand mycom = new SqlCommand(myinsert, sqlConnection);
        mycom.Parameters.AddWithValue("@Titel", textBox1.Text);
        mycom.Parameters.AddWithValue("@Inerpret", textBox2.Text);
        sqlConnection.Open();
        mycom.ExecuteNonQuery();
        mycom.Clone();
        mycom.Dispose();}

Show results:

enter image description here

enter image description here

Related