简体   繁体   English

获取动态创建的文本框的价值

[英]Get value of dynamically created textbox

I'm in a bit of a pickle at the moment, I've created a bit of code that creates 4 textboxes and adds them to a table layout at run time (code below) but I'm struggling with getting text from it, I tried getting the value from it as you would string s = TxtBox1.Text.ToString(); 我现在有点蠢,我创建了一些代码,创建了4个文本框,并在运行时将它们添加到表格布局中(下面的代码),但是我很难从中获取文本,我尝试从中获取值,因为你将string s = TxtBox1.Text.ToString(); but it just gets a null reference, then I tried txt.Text.ToString(); 但它只是得到一个空引用,然后我尝试了txt.Text.ToString(); and this just gets the text from the last text box that was created. 这只是从最后创建的文本框中获取文本。

   private void button2_Click(object sender, EventArgs e)
    {
        int counter;
        for (counter = 1; counter <= 4; counter++)
        {
            // Output counter every fifth iteration
            if (counter % 1 == 0)
            {
                AddNewTextBox();
            }
        }
    }

    public void AddNewTextBox()
    {
        txt = new TextBox();
        tableLayoutPanel1.Controls.Add(txt);
        txt.Name = "TxtBox" + this.cLeft.ToString();
        txt.Text = "TextBox " + this.cLeft.ToString();
        cLeft = cLeft + 1;
    }

I've looked all over for the answers to this and as of yet found nothing if anybody has any ideas I would be grateful. 我已经全神贯过地寻找答案了,但是如果有人有任何想法我什么都没发现我会感激不尽。

Thanks 谢谢

this code picks textbox1 from tableLayoutPanel1, cast it from Control to TextBox and takes Text property: 此代码从tableLayoutPanel1中选择textbox1,将其从Control转换为TextBox并获取Text属性:

string s = ((TextBox)tableLayoutPanel1.Controls["TxtBox1"]).Text;

if you need them all, then iterate over textboxes: 如果你需要它们,那么迭代文本框:

string[] t = new string[4];
for(int i=0; i<4; i++)
    t[i] = ((TextBox)tableLayoutPanel1.Controls["TxtBox"+(i+1).ToString()]).Text;

You can try 你可以试试

    var asTexts = tableLayoutPanel1.Controls
            .OfType<TextBox>()
            .Where(control => control.Name.StartsWith("TxtBox"))
            .Select(control => control.Text);

That will enumerate the Text value for all child controls of tableLayoutPanel1 where their type is TextBox and their name starts with "TxtBox". 这将枚举tableLayoutPanel1的所有子控件的Text值,其类型为TextBox,其名称以“TxtBox”开头。 You can optionally relax the filters removing the OfType line (that excludes any non TextBox control) or the Where line (that allow only the control which name matches your example). 您可以选择放宽过滤器,删除OfType行(排除任何非TextBox控件)或Where行(仅允许控件名称与您的示例匹配)。

Ensure to have 确保拥有

    Using System.Linq;

at the beginning of the file. 在文件的开头。 Regards, Daniele. 此致,Daniele。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM