2014-02-27 166 views
0

下面是在按鈕單擊時動態添加文本框和按鈕的代碼。我需要在另一個按鈕單擊時將tat文本框數據添加到數據庫。不知道這一點。任何建議都會有所幫助。將動態添加的文本框中的數據添加到數據庫

private void button1_Click(object sender, EventArgs e) 
{ 
    int v; 
    v = c++; 
    panel1.VerticalScroll.Value = VerticalScroll.Minimum; 

    Button btn = new Button(); 
    btn.Name = "btn" + v; 
    btn.Text = "Remove"; 
    btn.Location = new Point(300, 5 + (30 * v)); 
    btn.Click += new EventHandler(btn_Click); 

    TextBox txt = new TextBox(); 
    txt.Name = "TextBox" + v; 
    txt.Location = new Point(30, 5 + (30 * v)); 
    txt.Tag = btn; 

    TextBox txt1 = new TextBox(); 
    txt1.Name = "TextBox2" + v; 
    txt1.Location = new Point(170, 5 + (30 * v)); 
    txt1.Tag = btn; 

    panel1.Controls.Add(txt); 
    panel1.Controls.Add(txt1); 
    panel1.Controls.Add(btn); 
} 

private void btn_Click(object sender, EventArgs e) 
{ 
    for (int i = panel1.Controls.Count - 1; i >= 0; i--) 
    { 
     var item = panel1.Controls[i]; 

     if (item.Tag == sender || item == sender) 
      panel1.Controls.Remove(item); 
    } 
} 
+0

你能提供關於這方面的具體細節嗎?你有沒有數據庫交互的方法等? –

+0

要獲得文本框的文本,你可以使用這樣的東西。 'panel1.Controls [「nameOfTextbox」]。Text' – Patrick

回答

0

解決方案:您需要保存的動態TextBox控制的Name如下訪問他們面前:

List<String> controlNames=new List<String>(); 
TextBox txt = new TextBox(); 
txt.Name = "TextBox" + v; 
controlNames.Add(txt.Name); 
txt.Location = new Point(30, 5 + (30 * v)); 
txt.Tag = btn; 


TextBox txt1 = new TextBox(); 
txt1.Name = "TextBox2" + v; 
controlNames.Add(txt1.Name); 
txt1.Location = new Point(170, 5 + (30 * v)); 
txt1.Tag = btn; 

現在訪問它們,同時將數據保存到數據庫中

protected void btnSaveData_Click(object sender, EventArgs e) 
{ 

    //Read TextBox Values 
    TextBox txBox1 = (TextBox) Controls.Find(controlNames[0],true)[0]; 
    TextBox txtBox2 = (TextBox) Controls.Find(controlNames[1],true)[0]; 
    MySqlConnection con = new MySqlConnection("connection string here"); 
    String query="INSERT INTO [TABLENAME] ([COLUMNNAME1],[COLUMNNAME2]) VALUES(@COLUMNVALUE1 , @COLUMNVALUE2)"; 
    MySqlCommand command = new MySqlCommand(query,con); 

    command.Parameters.AddWithValue("@COLUMNNAME1",txBox1.Text); 
    command.Parameters.AddWithValue("@COLUMNNAME2",txBox2.Text); 

    int status=0; 
    con.Open(); 
    status = command.ExecuteNonQuery(); 

    if(status>0) 
    { 
     MessageBox.Show("Rows Inserted Successfully!"); 
    } 
    else 
    { 
     MessageBox.Show("No Rows Inserted!"); 
    } 

    con.Close(); 
} 
+0

textposws are dynamic added。我怎樣才能得到這樣的文本框的ID或名稱 – Robin

+0

@Robin:親愛的plese看到我編輯的答案。 –

+0

獲取錯誤,因爲方法'find'沒有超載 – Robin

相關問題