0

This is the code of my user control.

  <%@ Control Language="C#" AutoEventWireup="true" CodeBehind="NewUserControl.ascx.cs"           

  Inherits="usercontrol.NewUserControl" %>
  <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
  <asp:LinkButton ID="LinkButton1" runat="server"  onclick="LinkButton1_Click">LinkButton1</asp:LinkButton>  

and on another form on the button click event i am loaoding the user control.like this-

    protected void LoadControl_Click(object sender, EventArgs e)
    {
        newuc = LoadControl("NewUserControl.ascx") as NewUserControl;          
        form1.Controls.Add(newuc);
        Session["chksession"] = ((int)Session["chksession"]) + 1;

        if (((int)Session["chksession"]) >= 1)
        {
            for (int i = 1; i < ((int)Session["chksession"]); i++)
            {
                newuc = LoadControl("NewUserControl.ascx") as NewUserControl;
                form1.Controls.Add(newuc);
            }
        }
    }

now user control can be loaded any no of times, now i need the text of all the textboxes present on the form on the click of a Button that is present on the .aspx page. i am new to asp...need guidance.

4

1 回答 1

0

为什么不向您的 UserControl 添加一个允许您获取/设置文本的属性TextBox1

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

在您的按钮处理程序中像这样访问它:

newuc.Text = "Setting the text";
string myString = newuc.Text; //getting the text

更新:

由于您正在动态加载 UserControl,因此您必须将它们的值保存在 StateBag(ViewState、Session 等)中。

public string Text {
    get {
        //Default to any existing text
        string s = TextBox1.Text;
        //Use TextBox1.UniqueID to ensure a unique string for the ViewState key
        if (TextBox1.Text.Length == 0 & ViewState(TextBox1.UniqueID) != null) {
            //TextBox1.Text is empty, restore from ViewState
            s = ViewState(TextBox1.UniqueID).ToString;
        }
        return s;
    }
    set {
        //Set TextBox1.Text
        TextBox1.Text = value;
        //Store in ViewState as well
        ViewState(TextBox1.UniqueID) = TextBox1.Text;
    }
}
于 2013-01-07T18:48:35.217 回答