如何从动态文本框中保存数据?

时间:2014-01-05 07:04:35

标签: c# winforms textbox

此代码根据列表视图中的项目总数动态创建文本框。我的问题是如何访问这些文本框,以便我可以将文本框的内容保存到我的数据库?

int f = 24;
int j = 25;
for (int gg = 0; gg < listView1.Items.Count;gg++ )
{
 j = f + j;
 TextBox txtb = new TextBox();
 txtb.Name = "tboxl1"+gg;
 txtb.Location = new Point(330,j);
 txtb.Visible = true;
 txtb.Enabled = true;
 txtb.Font = new Font(txtb.Font.FontFamily,12);
 groupBox2.Controls.Add(txtb);
 }

3 个答案:

答案 0 :(得分:1)

我更倾向于写这样的代码:

var f = 24;
var j = 25;

var textBoxes =
    Enumerable
        .Range(0, listView1.Items.Count)
        .Select(gg =>
        {
            j = f + j;
            var txtb = new TextBox();
            txtb.Name = String.Format("tboxl1{0}", gg);
            txtb.Location = new Point(330, j);
            txtb.Visible = true;
            txtb.Enabled = true;
            txtb.Font = new Font(txtb.Font.FontFamily, 12);
            return txtb;
        })
        .ToList();

textBoxes.ForEach(txtb => groupBox2.Controls.Add(txtb));

现在您有一个变量textBoxes,用于保存对新文本框的引用。您可以使用它来从文本框中获取值,以将它们保存到数据库中。

答案 1 :(得分:1)

如果您想要所有TextBox控件:

        foreach (Control control in groupBox2.Controls)
        {
            if (control is TextBox)
            {
                string value = (control as TextBox).Text;
                // Save your value here...
            }
        }

但是如果你想要一个特定的TextBox,你可以通过它的名字得到它:

Control control =  groupBox1.Controls.Find("textBox1", false).FirstOrDefault(); // returns null if no control with this name exists
TextBox textBoxControl = control as TextBox; // if you want TextBox control
string value = control.Text;
// Now you can save your value anywhere

答案 2 :(得分:0)

您可以按如下方式获取对文本框的引用,

Control GetControlByName(string Name)
{
    foreach(Control c in this.Controls)
       if(c.Name == Name)
          return c;

    return null;
}