代码之家  ›  专栏  ›  技术社区  ›  Georgi Antonov

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

  •  0
  • Georgi Antonov  · 技术社区  · 9 年前

    这段代码运行良好,但它的INSERTING值仅来自textbox1、textbox2和Date2,如果我有更多的文本框和标签,如何在一次单击中插入不同控件中的多行。

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

    因此,在每一行上,我都需要textbox[i]textbox[i+1]Date[i+1]和全局变量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 回复  |  直到 9 年前
        1
  •  1
  •   Kryptonian    9 年前

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

        2
  •  0
  •   Dinesh Saxena    9 年前

    试试看这是否有效。

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