简体   繁体   English

在asp.NET C#中寻址动态创建的TextBox控件

[英]Addressing dynamically created TextBox Controls in asp.NET C#

I'm trying to make a page that loads an undefined number of rows into a table, each row containing two columns, one column a string, the other a TextBox. 我正在尝试创建一个将未定义行数加载到表中的页面,每行包含两列,一列包含字符串,另一列包含TextBox。 When I click a submit button, i want to be able to retrieve the values entered into each TextBox. 当我单击提交按钮时,我希望能够检索输入到每个TextBox中的值。

The first half i can do, obviously in the real code this would be in a foreach loop and the textbox ID assigned a unique value i could reproduce later to call it with. 上半部分我可以做,显然在实际代码中这将是一个foreach循环,文本框ID分配了一个唯一的值,我可以在以后重现它来调用它。

TableCell myCell = new TableCell();
myCell.Text = "StudentID";
TableCell nextCell = new TableCell();
TextBox mytext = new TextBox();
mytext.ID = "TxtBox1";
nextCell.Controls.Add(mytext);
TableRow myRow = new TableRow();
myRow.Cells.Add(myCell);
myRow.Cells.Add(nextCell);
TableStuUploads.Rows.Add(myRow);

When i click my submit button, i try to run this code(just temp code ATM, proof of concept stuff): 当我点击我的提交按钮,我尝试运行此代码(只是临时代码ATM,概念证明的东西):

TextBox tmptext = (TextBox)FindControl("TxtBox1");
Label1.Text = tmptext.Text;

But that sets tmptext as null, and i get a null pointer exception on the next line. 但是这会将tmptext设置为null,并且我会在下一行获得空指针异常。 So then i tried 所以我试过了

TextBox tmptext = (TextBox)TableStuUploads.FindControl("TxtBox1");
Label1.Text = tmptext.Text;

Same error. 同样的错误。 Then i tried 然后我试过了

foreach (Control x in TableStuUploads.Controls)
            {
                if (x.GetType().ToString().Equals("System.Web.UI.WebControls.TextBox"))
                {
                    Label1.Text = ((TextBox)x).Text;

                }
            }

But when debugging this, I see TableStuUploads.Controls has a count of zero. 但是在调试时,我看到TableStuUploads.Controls的计数为零。

How am I supposed to address these dynamically created controls? 我该如何处理这些动态创建的控件? I have searched around, and the answer i got lead me to the three solutions i have already tried. 我已经四处寻找了,我得到的答案就是我已经尝试过的三种解决方案。 Where am i going wrong? 我哪里错了?

You are probably not recreating your dynamic controls on post back. 您可能无法在回发时重新创建动态控件。 This is required to both find each control and retrieve each control's value. 这需要找到每个控件并检索每个控件的值。

In addition, it would probably be best to use a repeater to create these controls, It is easier to maintain and debug. 此外,最好使用转发器来创建这些控件,它更易于维护和调试。

Edit 编辑

You need to recreate your table on each postback(page_load) like @ShaiCohen says in his answer then you need something ilke: 你需要在每个回发(page_load)上重新创建你的表,就像@ShaiCohen在他的回答中说的那样你需要一些ilke:

foreach (TableRow item in TableStuUploads.Rows)
{               
     TextBox tmptext = (TextBox)item.FindControl("TxtBox1");
     Label1.Text = tmptext.Text;
}

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

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