Pass values from page to user control

前端 未结 5 1571
别那么骄傲
别那么骄傲 2021-02-14 07:21

I am storing name and last name in two labels in main page. I also have those values in a class (class doesnt do much but i am using them for future expansion). I have a user co

相关标签:
5条回答
  • 2021-02-14 08:01

    Step 1: You can expost the values as property and than you can make use of that easily.

    Step 2: To access your page from the user control you can make use of Parent property or may be some custome login to access the parent page and than write code to consume the property value.

    0 讨论(0)
  • 2021-02-14 08:05

    You need to create properties on your control to hold these values; then from the page code, simply assign the values to the properties in the control.

    On your control, you can have something like

    public string FirstName
    {
      get {
         if (ViewState["FirstName"] == null)
            return string.Empty;
         return ViewState["FirstName"].ToString();
    
          }
          set {
               ViewState["FirstName"] = value;
          }
    }
    
    0 讨论(0)
  • 2021-02-14 08:05

    you can do something like this in your user control

    string x=((yourparentcontrol)this.parent).label1.text;
    

    and use the string x.

    0 讨论(0)
  • 2021-02-14 08:14

    Create a property on your user control with the datatype of the data you want to pass to it, and populate it in your page on creation of the control.

    public class myUserControl : Control
        {
          ...
          public int myIntProperty {get; set;}
          ...
        }
    

    Later this in the code behind you can assign the value like

    myUserControl cntrl = new myUserControl();
        cntrl.myIntProperty = 5;
    

    Instead of this you can pass the value through Markup also like

    <uc1:myUserControl ID="uc1" runat="server" myIntProperty="5" />
    
    0 讨论(0)
  • 2021-02-14 08:22

    You need to define public properties on the control and then when you use control on the page you can pass values to those parameters.

    Something like:

    <cc:mycustomControl runat="server" 
        MyProperty1=<%# label1 %>
        MyProperty2=<%# label2 %>
    />
    
    0 讨论(0)
提交回复
热议问题