无法在asp.net中获取动态添加的用户控件的值

时间:2013-05-16 10:59:46

标签: c# asp.net user-controls

这是我的用户控件

<div class=" row-fluid">
<div class="span4" style="overflow: hidden;">
    <asp:DropDownList ID="ddlAccountName" runat="server" DataSourceID="ChartOfAccountsforVouchers"
        DataTextField="AccountName" DataValueField="ChartOfAccID">
    </asp:DropDownList>
   <%-- <asp:EntityDataSource ID="ChartOfAccountsforVouchers" runat="server" ConnectionString="name=CnFV1MainModelEntities"
        DefaultContainerName="CnFV1MainModelEntities" EnableFlattening="False" EntitySetName="ChartOfAccounts"
        Select="it.[ChartOfAccID], it.[AccountName]">
    </asp:EntityDataSource>--%>
</div>
<div class="span4">
    <asp:TextBox ID="txtValue" MaxLength="10" CssClass="numeric input-block-level" runat="server"></asp:TextBox>
</div>
<div class="span4">
    <asp:TextBox ID="txtValueB" MaxLength="10" CssClass="numeric input-block-level" runat="server"></asp:TextBox>
</div>

这就是我将此控件添加到占位符

的方式
int count = Convert.ToInt32(Session["AddedRows"]);
        ++count;
        for (int i = 0; i < count; i++)
        {
            // Add the usercontrol dynamically
            Control webUserControl = (Control)Page.LoadControl("ctrlEntryRows.ascx");
            placeRows.Controls.Add(webUserControl);
        }

        Session["AddedRows"] = count.ToString();

这就是按钮点击我试图获取控件的方式

if (placeRows.Controls.Count > 0)
            {
                foreach (Control ctrl in placeRows.Controls)
                {
                    TextBox txt = (TextBox)placeRows.FindControl("txtValue");
                    TextBox txtB = (TextBox)placeRows.FindControl("txtValueB");
                    string message = txt.Text + txtB.Text;
                }
            }

但代码显示0 count.IT甚至没有进入循环。如何获取动态添加的用户控件的值?

谢谢

1 个答案:

答案 0 :(得分:1)

试试这个

if (placeRows.Controls.Count > 0)
            {
                foreach (Control ctrl in placeRows.Controls)
                {
                    TextBox txt = (TextBox)ctrl.FindControl("txtValue");
                    TextBox txtB = (TextBox)ctrl.FindControl("txtValueB");
                    string message = txt.Text + txtB.Text;
                }
            }

更新:

你应该阅读一些关于动态控制和文章的文章。像这样的国家管理

  1. http://www.codeproject.com/Articles/3684/Retaining-State-for-Dynamically-Created-Controls-i
  2. http://www.4guysfromrolla.com/articles/092904-1.aspx
  3. Maintain the state of dynamically added user control on postback?