C# 动态文本字段在回发时不保留数据
我创建了一个webform,允许用户动态添加更多文本框。现在,当单击按钮添加另一个字段时,它会回发到自身。这些控件添加到Pre_Init中。但是,当页面自行重建时,文本框名称每次都不同,因此数据不会保留在每次回发中C# 动态文本字段在回发时不保留数据,c#,asp.net,controls,dynamic-controls,C#,Asp.net,Controls,Dynamic Controls,我创建了一个webform,允许用户动态添加更多文本框。现在,当单击按钮添加另一个字段时,它会回发到自身。这些控件添加到Pre_Init中。但是,当页面自行重建时,文本框名称每次都不同,因此数据不会保留在每次回发中 protected void Page_PreInit(object sender, EventArgs e) { MasterPage master = this.Master; //had to do this so that controls could be add
protected void Page_PreInit(object sender, EventArgs e)
{
MasterPage master = this.Master; //had to do this so that controls could be added.
createNewTextField("initEnumValue",true);
RecreateControls("enumValue", "newRow");
}
private int FindOccurence(string substr)
{
string reqstr = Request.Form.ToString();
return ((reqstr.Length - reqstr.Replace(substr, "").Length) / substr.Length);
}
private void RecreateControls(string ctrlPrefix, string ctrlType)
{
string[] ctrls = Request.Form.ToString().Split('&');
int cnt = FindOccurence(ctrlPrefix);
//Response.Write(cnt.ToString() + "<br>");
if (cnt > 0)
{
for (int k = 1; k <= cnt; k++)
{
for (int i = 0; i < ctrls.Length; i++)
{
if (ctrls[i].Contains(ctrlPrefix + k.ToString()) && !ctrls[i].Contains("EVENTTARGET"))
{
string ctrlID = ctrls[i].Split('=')[0];
if (ctrlType == "newRow")
{
createNewTextField(ctrlID,false);
}
break;
}
}
}
}
}
protected void addEnum_Click(object sender, ImageClickEventArgs e)
{
int cnt = FindOccurence("enumValue");
createNewTextField("enumValue" + Convert.ToString(cnt + 1),false);
// Response.Write(cnt.ToString() + "<br>");
}
private void createNewTextField(string ID, bool button)
{
Response.Write(ID + "<br/>"); //this is where I'm getting different names each time there is a postback
if (ID != "initEnumValue") //create new line starting with the second tb.
{
LiteralControl newLine = new LiteralControl();
newLine.Text = "<br />";
this.plhEnum.Controls.Add(newLine);
}
TextBox newTb = new TextBox();
newTb.ID = ID;
this.plhEnum.Controls.Add(newTb);
if (button) //create the button only on the first one.
{
LiteralControl space = new LiteralControl();
space.Text = " ";
this.plhEnum.Controls.Add(space);
ImageButton imgbutton = new ImageButton();
imgbutton.ID = "addEnum";
imgbutton.ImageUrl = "~/images/add.png";
imgbutton.Click += new ImageClickEventHandler(addEnum_Click);
imgbutton.CausesValidation = false;
this.plhEnum.Controls.Add(imgbutton);
}
//endEnumRow();
//this.plhEnum.Controls.Add(newTb);
}
我已经尝试过此解决方案创建Textbox控件后,能否将其保持在ViewState状态?因此,下次回发时,您无需创建它,只需通过访问ViewState将其添加到您可能要添加的面板中即可。请看,我不知道如何将其保持在ViewState中。我尝试通过.EnableViewState=true启用它;