如何从动态添加的用户控件中访问值?

时间:2013-09-27 06:21:54

标签: c# asp.net user-controls viewstate

我想从动态添加的用户控件中获取值

我正在尝试但计数为0因此条件失败

代码:

private const string VIEWSTATEKEY = "ContactCount";
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            //Set the number of default controls
            ViewState[VIEWSTATEKEY] = ViewState[VIEWSTATEKEY] == null ? 1 : ViewState[VIEWSTATEKEY];

            //Load the contact control based on Vewstate key
            LoadContactControls();
        }
    }


 private void LoadContactControls()
 {
    for (int i = 0; i < int.Parse(ViewState[VIEWSTATEKEY].ToString()); i++)
    {
        rpt1.Controls.Add(LoadControl("AddVisaControl.ascx"));
    }
 }

 protected void addnewtext_Click(object sender, EventArgs e)
 {
     ViewState[VIEWSTATEKEY] = int.Parse(ViewState[VIEWSTATEKEY].ToString()) + 1;
     LoadContactControls();
 }

修改

这里的问题计数为0,因此条件失败的循环出现

private void saveData()
{
    foreach (var control in rpt1.Controls)
        {
            var usercontrol = control as VisaUserControl;

            string visaNumber = usercontrol.TextVisaNumber;
            string countryName = usercontrol.VisaCountry;
        }
    }
}

protected void Save_Click(object sender, EventArgs e)
{
    saveData();
}

.ascx.cs

    public string TextVisaNumber
    {
        get { return txtUser.Text; }
        set { txtUser.Text = value; }
    }

    public string VisaCountry
    {
        get { return dropCountry.SelectedValue; }
        set { dropCountry.SelectedValue = value; }
    }

的.ascx

<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="AddVisaControl.ascx.cs" EnableViewState="false" Inherits="Pyramid.AddVisaControl" %>
<%@ Register assembly="BasicFrame.WebControls.BasicDatePicker" namespace="BasicFrame.WebControls" tagprefix="BDP" %>
<div id="divreg" runat="server">
<table id="tbl" runat="server">
    <tr>
    <td>
        <asp:Label ID="lbl2" runat="server"></asp:Label>
    </td>
</tr>
<tr>
<td> Visa Number:</td>
<td><asp:TextBox ID="txtUser" Width="160px" runat="server"/></td>
<td> Country Name:</td>
<td><asp:DropDownList ID="dropCountry" Width="165px" runat="server"></asp:DropDownList></td>
</tr>
<tr>
<td> Type of Visa:</td>
<td><asp:DropDownList ID="dropVisa" Width="165px" runat="server"></asp:DropDownList></td>
<td> Type of Entry:</td>
<td><asp:DropDownList ID="dropEntry" Width="165px" runat="server"></asp:DropDownList></td>
</tr>
<tr>
<td> Expiry Date</td>
    <td><BDP:BasicDatePicker ID="basicdate" runat="server"></BDP:BasicDatePicker></td>
<td>
<asp:Button ID="btnRemove" Text="Remove" runat="server" OnClick="btnRemove_Click" />
</td>
</tr>
</table>
</div>

有什么想法吗?提前致谢

2 个答案:

答案 0 :(得分:0)

您需要在用户控件中创建public property。 并通过用户控件的id访问该属性。 请参阅this和Th i的问题。

答案 1 :(得分:0)

始终为您正在添加其良好做法的控件分配ID。

Control ctrl = Page.LoadControl("~/UserControls/ReportControl.ascx");
ctrl.ID = "UniqueID";

此外,由于您要动态添加控件,因此您需要管理相同的视图状态,或添加为您执行此部分的第三方控件。