0

I have this basic WinForms application user interface:

enter image description here

And I want to add the data both to the DataGridView and the sql table, when the "Gem" button is clicked. I have this following code:

private void Form2_Load(object sender, EventArgs e)
    {
        try
        {
            con = new SqlConnection();
            con.ConnectionString = @"Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\Produkt.mdf;Integrated Security=True";
            con.Open();
            //adap = new SqlDataAdapter("select SN, FName as 'Navn', MName as 'Vare nr', LName as 'Antal', Age from Produkt", con);
            string sql = "SELECT Navn, Varenr, Antal, Enhed, Priseksklmoms, Konto FROM ProduktTable";

            adap = new SqlDataAdapter(sql, con);
            ds = new System.Data.DataSet();
            adap.Fill(ds, "ProduktTable");
            dataGridView1.DataSource = ds.Tables["ProduktTable"];

        }

        catch (Exception ex)
        {
            MessageBox.Show("Error\n" + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }

    }

private void button1_Click(object sender, EventArgs e)
    {
        string navn = textBox2.Text;
        int varenr = int.Parse(textBox3.Text);
        float antal = (float)Convert.ToDouble(textBox4.Text);
        string enhed = textBox5.Text;
        string konto = comboBox2.Text;
        float pris = (float)Convert.ToDouble(textBox6.Text);

        dataGridView1.Rows[0].Cells[0].Value = navn;
        dataGridView1.Rows[0].Cells[1].Value = varenr;

        string StrQuery;

        try
        {

            SqlCommand comm = new SqlCommand();
            comm.Connection = con;

           for (int i = 0; i < dataGridView1.Rows.Count; i++)
            {
                StrQuery = @"INSERT INTO ProduktTable VALUES ('"
                + dataGridView1.Rows[i].Cells[0].Value + "',' "
                + dataGridView1.Rows[i].Cells[1].Value + "');";
                comm.CommandText = StrQuery;                  
                comm.ExecuteNonQuery();                    
            }

        }
        catch (Exception ex)
        {
            MessageBox.Show("Error\n" + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }

This is just an example with the purpose for storing the string "navn" and the integer "Varenr" in the DataGridView and the sql. When Im running the application and clicking on the button, following error occurs:

enter image description here

My column names for my ProduktTable table are exactly the same as the column names for the dataGridView.

Thanks in advance

4
  • have you tried to set a break point on your for statement to check whether the loop is not out of the range of your database fields ? Commented Jun 6, 2014 at 0:14
  • Yes. It throws the error in the first time it reaches the comm.ExecuteNonQuery() line. Commented Jun 6, 2014 at 0:31
  • 1
    Please STOP concatenating together your SQL statements! This is a huge security risk and opens the doors for SQL injection attacks! Just don't do it - EVER. Instead, use parametrized queries - ALWAYS, no exception Commented Jun 6, 2014 at 6:54
  • Bad habits to kick: using SELECT * / omit the column list Commented Jun 6, 2014 at 6:54

1 Answer 1

1

Explicitly set your column names in the insert statement...

StrQuery = @"INSERT INTO ProduktTable (Navn, Varenr) VALUES ('"
                + dataGridView1.Rows[i].Cells[0].Value + "',' "
                + dataGridView1.Rows[i].Cells[1].Value + "');";
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.