【问题标题】:Get value from a user control that add dynamically in asp.net从在 asp.net 中动态添加的用户控件中获取值
【发布时间】:2014-04-07 11:12:17
【问题描述】:

我想通过单击按钮来添加一些控件。再次单击时,此控件会重复。然后点击另一个按钮保存所有控件的值。

所以我使用具有此控件的用户控件(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);
        }
    }

如何从这个用户控件获取数据?

【问题讨论】:

    标签: c# asp.net user-controls


    【解决方案1】:

    我假设您的“SaveFilters”方法在网络表单回发时被调用,无论是来自页面加载事件还是来自导致回发的事件(例如按钮单击事件)。

    如果您希望能够读取它们的值,则需要在每次回发时重新加载所有动态控件。典型的模式是从 Page Init 事件添加动态控件。 Asp.Net 运行时在 Page Init 之后将值分配给表单中的控件。您可以从 Page Load 事件或导致回发的事件(例如按钮单击事件)中读取这些值。

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

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

    【讨论】:

    • 我在 init 中添加了 CreateControls() 但没有再次工作并且 placeholder.controls.count 为 0。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-11
    • 2014-12-09
    • 1970-01-01
    • 2011-04-13
    • 2011-03-14
    • 2012-05-31
    相关资源
    最近更新 更多