Search code examples
c#datagridviewnpgsql

Insert value from datagridview to sql


I would like insert data from datagridview to database but it didn't happen First button import data from xls and second button should insert all data to db not only one record. How i can fix it?

    private void button8_Click(object sender, EventArgs e)
    {
        string stringconn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + textBox2.Text + ";Extended Properties=\"Excel 8.0;HDR=Yes;\";";
        OleDbConnection cons = new OleDbConnection(stringconn);
        OleDbDataAdapter dat = new OleDbDataAdapter("Select * from [Sheet1$]", cons);
        dat.Fill(dt);

        dataGridView1.DataSource = dt;
    }

    private void button9_Click(object sender, EventArgs e)
    {
        try
        {
            load();
            conn.Open();
            string col1 = dataGridView1[0, dataGridView1.CurrentCell.RowIndex].Value.ToString();
            string col2 = dataGridView1[1, dataGridView1.CurrentCell.RowIndex].Value.ToString();
            string col3 = dataGridView1[2, dataGridView1.CurrentCell.RowIndex].Value.ToString();

            string insert_sql = "INSERT INTO humans VALUES('" + col1 + "','" + col2 + "','" + col3 + "')";

            da = new NpgsqlDataAdapter(insert_sql, conn);
            da.SelectCommand.ExecuteNonQuery();

            conn.Close();
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }

Solution

  • Maybe the problem is with the datatype because the columns values is string so you should pass the string values like following, try this:

     string query = "Insert into [User].[dbo].[songsN1] (songsName,path) Values (@c1,@c2,c3)";
                    command.Parameters.AddWithValue("@c1", col1);
                    command.Parameters.AddWithValue("@c2",col2);
                    command.Parameters.AddWithValue("@c3", col3);