0

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

我正在尝试,但计数为 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>

有任何想法吗?提前致谢

4

2 回答 2

1

您需要在用户控件中创建公共属性。并通过用户控件的 id 访问该属性。看到这个的问题。

于 2013-09-27T06:26:38.710 回答
0

始终将 id 分配给要添加的控件,这是一种很好的做法。

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

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

于 2013-09-27T06:33:18.453 回答