【问题标题】:Storing Data from Multiple textboxes created dynamically从动态创建的多个文本框中存储数据
【发布时间】:2015-09-21 19:10:12
【问题描述】:

我使用了一个按钮来创建一组文本框,如下所示:

public partial class Form1 : Form
    {
        private int a = 75;
        public Form1()
        {
            InitializeComponent();
        }
        private void button1_Click(object sender, EventArgs e)
        {
            this.textBox1 = new System.Windows.Forms.TextBox();
            this.textBox1.Location = new System.Drawing.Point(50, a);
            this.textBox1.Name = "textBox1";
            this.textBox1.Size = new System.Drawing.Size(100, 20);
            this.textBox1.TabIndex = 0;
            this.Controls.Add(this.textBox1);

            this.textBox2 = new System.Windows.Forms.TextBox();
            this.textBox2.Location = new System.Drawing.Point(200, a);
            this.textBox2.Name = "textBox2";
            this.textBox2.Size = new System.Drawing.Size(100, 20);
            this.textBox2.TabIndex = 0;
            this.Controls.Add(this.textBox2);

            this.button1.Location = new System.Drawing.Point(650, a);
            a += 25;
        }
  }

因此,可能会为许多按钮点击创建许多 textbox1 和 textbox2。说 10 textbox1 和 10 textbox2。如何从所有这些中获取数据并存储在数据库中。每个 textbox1 和 textbox2 都在一行表格中?

欢迎任何帮助。

【问题讨论】:

    标签: c# textbox


    【解决方案1】:

    首先:我认为您正在寻找DataGrid

    如果没有,则需要采取几个步骤。首先,textbox1textbox2 是类的成员,而不是方法的成员,因此每次单击时,您都会一次又一次地编辑相同的文本框。要创建新的文本框,请使用

    TextBox newBox = new TextBox();  
    

    在方法内部并继续使用它而不是this.textbox1(或textbox2)。请记住,每次单击按钮时都应更改为 TextBoxes 的位置,以免它们重叠。您可以使用类变量作为点击次数。

    我认为最简单的方法是将创建的文本框存储在一个集合中,例如字典:

    public partial class...
    {
        Dictionary<TextBox, TextBox> tbPairs = new Dictionary<TextBox, TextBox>();
    
        private void button1_Click(...)
        {
    
        ... //create newBox1 and newBox2
    
        tbPairs[newBox1] = newBox2;   //adds the Pair to the Dictionary
        }
    }
    

    要在填充文本框后调用字典的内容,请使用

    foreach (KeyValuePair<TextBox, TextBox> in tbPairs)  
    {  
        ... //write to Server here - but that is an issue too big for handling here - look it up
    }
    

    关于如何将数据写入数据库,请查看如何使用SqlCommands

    【讨论】:

      猜你喜欢
      • 2019-01-04
      • 1970-01-01
      • 1970-01-01
      • 2013-05-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-02-26
      相关资源
      最近更新 更多