简体   繁体   English

如何获取动态生成的usercontrol控件的属性值?

[英]How to get the property value of dynamically generated usercontrol's control?

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. 现在可以随时加载用户控件,现在我需要单击.aspx页面上存在的按钮,然后单击窗体上存在的所有文本框的文本。 i am new to asp...need guidance. 我是新手,需要指导。

Why not add a property to your UserControl that allows you to get/set the text in TextBox1 : 为什么不向您的UserControl添加一个属性,该属性允许您获取/设置TextBox1的文本:

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

Access it like this in your button handler: 在按钮处理程序中像这样访问它:

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

UPDATE: 更新:

Since you're loading the UserControls dynamically, you'll have to persist their values in a StateBag (ViewState, Session, etc.). 由于要动态加载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;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM