Asp.net access controls of user control from aspx

2019-08-12 16:28发布

I have a user control and it has a method which is executed when button on aspx page is clicked, I m passing two ids of the user control in the method, Now i want to get the values of the textbox in the user control but unfortunately it is not recognizing textbox I have coded :-

 //Method to copy values from one control into another
        public void copyInfo(Control ctrl1, Control ctrl2) {  
            List<string> vals = new List<string>();
            foreach (Control c in ctrl1.Controls)
            {
                if (c is TextBox)
                {    
                    if (string.IsNullOrEmpty(((TextBox)c).Text)) { }
                    else {
                   //values from textbox
                        vals.Add(((TextBox)c).Text);
                    }
                }

                              .............
                                ..........
                                  ......

how can i get the textbox control and there values.

1条回答
爷、活的狠高调
2楼-- · 2019-08-12 17:10

I would add a public property on your UserControl such as:

public string SomeTextboxValue
{
  get
  {
    return SomeTextBox.Text;
  }

  set
  {
    SomeTextBox.Text = value;
  }
}

Then you need to cast your controls into their actual types rather than the generic Control class:

SomeControl someControl1 = (SomeControl)ctrl1;
SomeControl someControl2 = (SomeControl)ctrl2;
someControl1.SomeTextboxValue = someControl2.SomeTextboxValue;

Or the other way around depending on which your from and dest are in the copy.

Update to discuss dynamic controls

If your controls are being dynamically created and you can't find it on postback its probably because you haven't recreated the controls on postback. I have found this article series to be very interesting when trying to understand how to work with and process data from dynamic controls:

That link is to part three but its where the important part is which covers your scenario:

Creating the Custom Client Attribute UI and Loading the Client's Current Values from the Database

When programmatically adding Web controls to an ASP.NET page it is essential that the controls are added to the page on each and every page visit. This includes the first page visit and all subsequent postbacks.

查看更多
登录 后发表回答