按钮单击时在表中插入多行

时间:2015-08-05 03:30:59

标签: c# sql .net sql-server-ce

此代码工作正常,但其INSERTING值仅来自textbox1 textbox2和Date2如果我有更多文本框并标记如何在一次单击中插入来自不同控件的多行,该怎么办。

准确地说,我有10对文本框文本框1和文本框2然后文本框3和文本框4和10标签 日期2/4/6/8

所以在每一行我想要来自textbox [i] textbox [i + 1] Date [i + 1]和global varialbe buyEUR

的值
private void InsertData_Click(object sender, EventArgs e)
{

    SqlCeConnection connection = new SqlCeConnection(@"Data Source=C:\Users\FluksikartoN\Documents\Visual Studio 2012\Projects\BuroFoki\BuroFoki\MainDB.sdf");
    connection.Open();

    using (SqlCeCommand com = new SqlCeCommand("INSERT INTO TenOperations (EUR, Rate, BGN, Date) Values(@EUR, @Rate, @BGN, @Date)", connection))
    {
       /* for (int i = 2; i <= 20; i = i+2)
       {
          TextBox txtBox1 = this.Controls["TextBox" + (i - 1).ToString()] as TextBox;
          TextBox txtBox2 = this.Controls["TextBox" + i.ToString()] as TextBox;
          Label Date = this.Controls["Date" + i.ToString()] as Label;*/
          com.Parameters.AddWithValue("@EUR", textBox2.Text.ToString());
          com.Parameters.AddWithValue("@Rate", EURbuy);
          com.Parameters.AddWithValue("@BGN", textBox1.Text.ToString());
          com.Parameters.AddWithValue("@Date", Date2.Text.ToString());
          /*
          com.Parameters.AddWithValue("@EUR", textBox4.Text.ToString());
          com.Parameters.AddWithValue("@Rate", EURbuy);
          com.Parameters.AddWithValue("@BGN", textBox3.Text.ToString());
          com.Parameters.AddWithValue("@Date", Date4.Text.ToString());
          */
          com.ExecuteNonQuery();

       }

       connection.Close();

     }

2 个答案:

答案 0 :(得分:1)

您可以创建一个控件数组See here(虽然没有固有支持可以复制功能)然后您可以使用循环将值添加为参数并将值插入数据库中。

答案 1 :(得分:0)

尝试这是否有效。

using (SqlCeCommand com = new SqlCeCommand("INSERT INTO TenOperations (EUR, Rate, BGN, Date) Values(@EUR1, @Rate1, @BGN1, @Date1),(@EUR2, @Rate2, @BGN2, @Date2)", connection))
     {
        com.Parameters.AddWithValue("@EUR1", textBox2.Text.ToString());
        com.Parameters.AddWithValue("@Rate1", EURbuy);
        com.Parameters.AddWithValue("@BGN1", textBox1.Text.ToString());
        com.Parameters.AddWithValue("@Date1", Date2.Text.ToString());

        com.Parameters.AddWithValue("@EUR2", textBox4.Text.ToString());
        com.Parameters.AddWithValue("@Rate2", EURbuy);
        com.Parameters.AddWithValue("@BGN2", textBox3.Text.ToString());
        com.Parameters.AddWithValue("@Date2", Date4.Text.ToString());

        com.ExecuteNonQuery();
     }
相关问题