0

我有一个表单,其中我有一个组合框,其中填充了表的列名我有一个文本框我打算输入值,当我单击保存按钮时,我希望将数据插入到具有被选中。

这是我的代码。

private void button1_Click(object sender, EventArgs e)
{
   try
   {
       myConnection.ConnectionString = "Data Source = AmiayaEjay-Vaio; Initial Catalog = RealTime; User ID = sa; Password = admin";

       String combo1 = comboBox1.SelectedItem.ToString();
       String combo2 = comboBox2.SelectedItem.ToString();
       String combo3 = comboBox3.SelectedItem.ToString();
       String combo4 = comboBox4.SelectedItem.ToString();
       String combo5 = comboBox5.SelectedItem.ToString();
       String combo6 = comboBox6.SelectedItem.ToString();
       String combo7 = comboBox7.SelectedItem.ToString();
       String combo8 = comboBox8.SelectedItem.ToString();

       query1.CommandText = "insert into dbo.DepthTable ( '" + combo1 + "','" + combo2 + "','" + combo3 + "','" + combo4 + "','" + combo5 + "','" + combo6 + "' ,'" + combo7 + "','" + combo8 + "') values ('" + textBox1.Text + "','" + textBox2.Text + "','" + textBox3.Text + "','" + textBox4.Text + "','" + textBox5.Text + "','" + textBox6.Text + "','" + textBox7.Text + "','" + textBox8.Text + "')";

       query1.CommandType = CommandType.Text;
       query1.Connection = myConnection;

       myConnection.Open();
       query1.ExecuteNonQuery();
   }
   catch (Exception ex)
   {
       throw ex;
   }

   myConnection.Close();
}

我不断收到错误消息说我有无效的列名,因为 sql 命令看不到 combo1-combo8 有一个有效的列名

4

1 回答 1

3

删除comboX 中的“'”符号。

"insert into dbo.DepthTable (" + combo1 + "," + combo2 + "," + combo3 + "," + combo4 + "," + combo5 + "," + combo6 + "," + combo7 + "," + combo8 + ") values ('" + textBox1.Text + "','" + textBox2.Text + "','" + textBox3.Text + "','" + textBox4.Text + "','" + textBox5.Text + "','" + textBox6.Text + "','" + textBox7.Text + "','" + textBox8.Text + "')";
于 2012-07-17T15:35:58.443 回答