我的页面上有很少的文本框,这些文本框是在下拉列表中的文本更改时动态加载的。 用户在这些文本框中输入值并单击addnewitem按钮。在后面的代码中,我想捕获在这些文本框中输入的值。但我得到的值是空的。
On Pageload mthd没有任何内容引用createdynamiccontrols方法。然后我
protected override void CreateChildControls()
{
base.CreateChildControls();
CreateDynamicControls();
}
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
}
protected override object SaveViewState()
{
return new Pair(base.SaveViewState(), null);
}
protected override void LoadViewState(object savedState)
{
base.LoadViewState(((Pair)savedState).First);
EnsureChildControls();
}
public void CreateDynamicControls()
{
Student= ddlStudentschool.SelectedItem.Text.ToString();
studentcollege= ddlstudentcollege.SelectedValue.ToString();
int rowPos = 0;
DynPanel.BorderStyle = BorderStyle.Solid;
根据所选的studentchool和studentcollege,以下文本框和&将创建字段名
Label Mynewlabel = new Label();
Mynewlabel.ID = "lbl" + FldLabel;
Mynewlabel.Text = FldLabel;
Mynewlabel.Visible = true;
Mynewlabel.Font.Bold = true;
DynPanel.Controls.Add(new LiteralControl("<td bgcolor=#333>"));
DynPanel.Controls.Add(Mynewlabel);
DynPanel.Controls.Add(new LiteralControl("</td>"));
if (ControlType == "TextBox")
{
int textBoxLength;
TextBox MynewTextBox = new TextBox();
MynewTextBox.ID = "txt" + Fldname;
MynewTextBox.Width = 100;
MynewTextBox.EnableViewState = true;
MynewTextBox.Enabled = true;
did not paste the whole code
}
protected void DropDownList1_SelectedIndexChanged1(object sender, EventArgs e)
{
CreateDynamicControls();
}
protected void btnAddItem_Click(object sender, EventArgs e)
{
CreateDynamicControls();
if (DynPanel.Controls != null)
{
foreach (Control ctrl in DynPanel.Controls)
{
if (ctrl is TextBox)
{
TextBox _txt = DynPanel.FindControl(ctrl.ID) as TextBox;
int count = DynPanel.Controls.Count;
// txtresult.ID = ctrl.ID;
txtresult.Text = ((TextBox)ctrl).Text;
TextBox txtPath = (TextBox)ctrl.FindControl("");
string result = txtresult.Text;
}
首先,当第二次调用createchildcontrols方法时,我没有将对象引用设置为对象的实例,并且如果我在additem click事件中没有createdynamiccontrols方法,则控件不再是tehre ...
答案 0 :(得分:0)
这可能与你如何加载控件有关。在回发后,您需要将动态控件重新加载到最初加载的相同位置。否则视图状态将不匹配,并且控制状态无法加载到控制树中。如果这不起作用,请发布更多代码!
答案 1 :(得分:0)
您需要re-create dynamic control on each postback,查看我之前对类似问题的回答here