获取动态创建的文本框的价值 [英] Get value of dynamically created textbox

查看:52
本文介绍了获取动态创建的文本框的价值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此刻我有点不高兴,我创建了一些代码,该代码创建了4个文本框,并在运行时将它们添加到表布局中(如下代码),但是我在获取文本方面很挣扎从中,我尝试从中获取值,就像您 string s = TxtBox1.Text.ToString(); 一样,但是它只是得到一个空引用,然后我尝试了 txt.Text.ToString(); ,这只是从创建的最后一个文本框中获取文本。

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(); but it just gets a null reference, then I tried 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.

谢谢

推荐答案

此代码从tableLayoutPanel1中选择textbox1,将其从Control转换为TextBox并采用Text属性:

this code picks textbox1 from tableLayoutPanel1, cast it from Control to TextBox and takes Text property:

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;

这篇关于获取动态创建的文本框的价值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆