访问文本框 ID [英] Accessing TextBox ID

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

问题描述

我有一种方法可以在每次点击按钮时创建文本框.但是,我正在尝试以另一种方法访问 Textbox ID.有些东西似乎超出了范围,这是代码:

I have a method that creates Textboxes each time the button is clicked. However I am trying to access the Textbox ID in another method. Something seems to be out of scope, here is the code:

    public partial class _Default : System.Web.UI.Page
{
    TextBox box = new TextBox();

    protected void Page_Load(object sender, EventArgs e)
    {



    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        ViewState["count"] = Convert.ToInt32(ViewState["count"]) + 1;
        Label1.Text = ViewState["count"].ToString();
        int test = int.Parse(string.Format("{0}", ViewState["count"]));

            for (int j = 0; j < test; j++)
            {

                TableRow r = new TableRow();

                box.ID = "Textbox" + j;

                TableCell c = new TableCell();
                c.Controls.Add(box);
                r.Cells.Add(c);
                table1.Rows.Add(r);
                Response.Write(box.ID);

            }

            if (test == 4)
            {
                Button1.Visible = false;
            }

    }

    protected void Button2_Click(object sender, EventArgs e)
    {

        Response.Write(box.ID);
    }

我希望 Button2_Click 打印出 box.ID 以确保它能够访问它.

I would like to Button2_Click to print out the box.ID to make sure it's able to access it.

推荐答案

在您的 Page_Load 中,始终创建与用户单击 Button1 的次数一样多的文本框你必须运行代码:

To always create as many text boxes as the number of times user clicked Button1, in your Page_Load you have to run code:

int test = 0;
if (ViewState["count"] != null)
   test = (int)ViewState["count"];

for (int j = 0; j < test; j++)
{
    TextBox box = new TextBox();
    box.ID = "Textbox" + j;
    textBoxes.Add(box.ID, box);
    TableRow r = new TableRow();
    TableCell c = new TableCell();
    c.Controls.Add(box);
    r.Cells.Add(c);
    table1.Rows.Add(r);
}

其中 textBoxesPage 类成员:

where textBoxes is a Page class member:

Dictionary<string, TextBox> textBoxes = new Dictionary<string, TextBox>();

然后,在 Button2_Click 中:

string ids = "";
foreach(string id in textBoxes.Keys)
{
    ids = ids + id + ",";
}
Response.Write(ids);

这篇关于访问文本框 ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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