我想点击按钮添加一些控件。再次单击时,此控件重复进行。然后单击另一个按钮保存所有控件的值。
所以我使用具有此控件的usercontrol(FilterParameters):
<div class="main">
<asp:label ID="FilterByParam" runat="server" Text="filter" ></asp:label>
<asp:TextBox ID="txtFilter" runat="server" CssClass="NormalTextBox" Width="200px"></asp:TextBox>
</div>
<div class="main">
<asp:label ID="FilterRule" runat="server" Text="Rule"></asp:label>
<asp:TextBox ID="txtRule" runat="server" Width="330px" Height="50px" TextMode="MultiLine"></asp:TextBox>
</div>
我在我的代码中使用此代码来加载此用户控件(我添加一个占位符来添加此usercontrol):
protected void lnkAddNew_Click(object sender, EventArgs e)
{
int count = 0;
if (ViewState["count"] != null)
{
count = (int)ViewState["count"];
}
count++;
ViewState["count"] = count;
CreateControls();
}
private void CreateControls()
{
int count = 0;
if (ViewState["count"] != null)
{
count = (int)ViewState["count"];
}
while (placeholder.Controls.Count < count)
{
Common.FilterParameters fp = (Common.FilterParameters)LoadControl("~/Common/FilterParameters.ascx");
fp.ID = "fp" + placeholder.Controls.Count.ToString();
placeholder.Controls.Add(fp);
}
}
此控件小心加载。但我从这个控件保存数据有问题。我使用此代码但没有用。 (placeholder.controls.count始终为0)
private void SaveFilters()
{
int count = 0;
if (ViewState["count"] != null)
{
count = (int)ViewState["count"];
}
string str=string.Empty;
for (int i = 0; i <= placeholder.Controls.Count; i++)
{
Common.FilterParameters fp = (Common.FilterParameters)placeholder.FindControl("fp"+i.ToString());
if(fp!=null)
{
string param = fp.filterparamText;
string rule = fp.RuleText;
str+="{"+param+"+"+rule+"}";
}
}
if(!string.IsNullOrEmpty(str))
{
save(str);
}
}
如何从此用户控件获取数据?
答案 0 :(得分:0)
我假设当webform从页面加载事件或导致回发的事件(例如按钮单击事件)回发时,正在调用“SaveFilters”方法。
如果您希望能够读取其值,则需要在每次回发时重新加载所有动态控件。典型的模式是从Page Init事件添加动态控件。 Asp.Net运行时在Page Init之后从表单中为控件分配值。您可以从Page Load事件或导致回发的事件中读取这些值(例如,按钮单击事件)。
如果不重新添加动态控件,Asp.net运行时无处可放置表单中的值,因此这些值会丢失。
因此,对于动态控件: 1.每次页面回发时,将它们加载到Page Init事件中。 2.在页面加载事件中或在导致回发的事件中读取它们的值(例如按钮单击事件)。