2014-06-06 19 views
0

我有這個基本的WinForms應用程序的用戶界面:添加數據

enter image description here

而且我希望將數據添加兩到DataGridView和SQL表,單擊「創業板」按鈕時。我有這樣的下面的代碼:

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); 
     } 

這僅僅是與宗旨,爲存儲字符串「navn」,並在DataGridView和SQL整數「Varenr」的一個例子。當進出口運行應用程序並點擊按鈕,會出現以下錯誤:

enter image description here

我ProduktTable表我的列名是完全一樣的DataGridView的列名。

在此先感謝

+0

你試圖設置你的**一個破發點的**語句來檢查是否循環沒有超出數據庫字段的範圍? –

+0

是的。它在第一次到達comm.ExecuteNonQuery()行時引發錯誤。 –

+1

請**停止**連接您的SQL語句!這是一個巨大的**安全風險,併爲SQL注入攻擊打開大門!只是**不這樣做 - 永遠**。相反,使用**參數化查詢** - **始終**,沒有例外 –

回答

1

在INSERT語句明確設置列名...

StrQuery = @"INSERT INTO ProduktTable (Navn, Varenr) VALUES ('" 
       + dataGridView1.Rows[i].Cells[0].Value + "',' " 
       + dataGridView1.Rows[i].Cells[1].Value + "');"; 
+0

謝謝,它的工作原理,但我的數據庫表仍然是空的。 –