2014-04-07 71 views
0

我想通过单击按钮添加一些控件。当再次点击时,这个控制重复。然后点击另一个按钮保存所有控件的值。从在asp.net中动态添加的用户控件获取值

所以我用一个用户控件(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> 

,我使用此代码在我的代码加载该用户控件(我添加了一个占位符添加这个用户控件):

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

我假设你的“SaveFilters”方法在webform发布时从页面加载事件或从导致回发的事件(例如按钮单击事件)回发时被调用。

如果您希望能够读取其值,则需要在每次回发中重新加载所有动态控件。典型的模式是从Page Init事件添加动态控件。在页面初始化之后,Asp.Net运行时从窗体中为控件赋值。您可以从页面加载事件或导致回发的事件(例如按钮单击事件)中读取这些值。

如果您不重新添加动态控件,则Asp.net运行时无法放置表单中的值,因此这些值将丢失。

因此,对于动态控件: 1.每当页面回传时,将它们加载到Page Init事件中。 2.在页面加载事件或导致回发的事件(例如按钮单击事件)中从它们读取值。

+0

我在init中添加CreateControls(),但不再工作,placeholder.controls.count为0。 – atabrizi

相关问题