我改变了我的问题,因为它可能没有被理解。也对不起我的英语...
动态创建将它们放入数组中的文本框。
我的一段代码:
public partial class NewArticleForm : System.Web.UI.Page
{
private Label[] lblName;
private TextBox[] txtName;
private Label[] lblSurname;
private TextBox[] txtSurname;
private PlaceHolder PlaceHolder1;
public int NumberOfOtherAuthors()
{
Int32 index = Convert.ToInt32(NumberList.SelectedValue);
return index;
}
public void dataofOtherAuthor()
{
int authors;
int i = 0;
int j=1
authors = NumberOfOtherAuthors();
lblName = new Label[authors];
txtName = new TextBox[authors];
lblSurname = new Label[authors];
txtSurname = new TextBox[authors];
PlaceHolder1 = new PlaceHolder();
for (i = 0; i < authors; i++)
{
Label authorInformation = new Label();
authorInformation.Text = "Information for Author " + j.ToString() + " :";
lblName[i] = new Label();
lblName[i].Text = "Name:";
txtName[i] = new TextBox();
lblSurname[i] = new Label();
lblSurname[i].Text = "Surname:";
txtSurname[i] = new TextBox();
PlaceHolder1.Controls.Add(authorInformation);
PlaceHolder1.Controls.Add(lblName[i]);
PlaceHolder1.Controls.Add(txtName[i]);
PlaceHolder1.Controls.Add(lblSurname[i]);
PlaceHolder1.Controls.Add(txtSurname[i]);
// Add a spacer in the form of an HTML <BR> element.
Panel1.Controls.Add(PlaceHolder1);
j++; } }
protected void NumberList_SelectedIndexChanged(object sender, EventArgs e)
{
dataofOtherAuthor();
}
private void UploadForm()
{
int numberOfOtherAuthors = NumberOfOtherAuthors();
int i=0;
for (i = 0; i < numberOfOtherAuthors; i++)
{
Label1.Text = txtName[i].Text;
}
}
protected void btnUpload_Click(object sender, EventArgs e)
{
UploadForm();
}
}
如何获取文本框的值??具体来说,我想将数据传递到数据库中。 Label 是一个测试,如果我得到值。
谢谢!!!
不确定您是否知道,但是您在 for 循环的每次迭代中都将 PlaceHolder1
放在 Panel1
中。也许您打算在 for 循环之后执行 Panel1.Controls.Add(PlaceHolder1);
?
不管怎样,您已经将这些 TextBox 控件放入窗体中。如果您尝试通过回发访问它们,您需要通过它们的设置 ID
访问它们,或者通过它们的 asp 容器访问它们(同时设置 runat="server"
):
x = (p1.Controls[placeHolderIndex].Controls[textBoxIndex] as TextBox).Text;
或者你可以试试
x = (p1.FindControl("placeHolder_ID").FindControl("textBox_ID") as TextBox).Text;
再次确保它们都是 runat="server"
txtName
将不会在回发后保留其值。
让你的第二个循环做一些比覆盖设置字符串更有用的事情;也许将每个值添加到列表中
List<string> x = new List<string>();
for (i = 0; i < authors; i++)
{
x.Add((p1.Controls[placeHolderIndex].Controls[i] as TextBox).Text);
//increment placeHolderIndex if you don't change your design
}
我是一名优秀的程序员,十分优秀!