We help IT Professionals succeed at work.

Set variable to object already on aspx page

eshurak
eshurak asked
on
Medium Priority
366 Views
Last Modified: 2012-03-13
Hello Experts,

I think this is an easy one.  I need to set a variable to an object already my aspx.  Here's my code it's called during the page_load event.

        private void LoadSearchComboBoxs(string ComboName)
        {
            ComboBox TheComboBox;
            TheComboBox = Page.Controls[ComboName];
}

Open in new window


Thanks
Comment
Watch Question

Kyle AbrahamsSenior .Net Developer
CERTIFIED EXPERT
Commented:
TheComboBox = Page.FindControl(ComboName.ClientID);
CERTIFIED EXPERT
Most Valuable Expert 2011
Top Expert 2015
Commented:
Since you declared the reference TheComboBox to be of type ComboBox, you need to cast the thing returned by the indexing of the Controls collection (which returns "things" as type Control). In other words:

TheComboBox = (ComboBox)Page.Controls[ComboName];

Open in new window

CERTIFIED EXPERT
Most Valuable Expert 2011
Top Expert 2015

Commented:
...ged325's solution would require the same, for the same reason  = )

Author

Commented:
Kaufmed - Thanks for your input.  I'm using:

            ComboBox TheComboBox;
            TheComboBox = (ComboBox)Page.Controls[ComboName];

But I'm getting the following errors

The best overloaded method match for 'System.Web.UI.ControlCollection.this[int]' has some invalid arguments      
Argument '1': cannot convert from 'string' to 'int'      

Is there a better way of doing declaring my object variable?
Hi,

Try this,

ComboBox TheComboBox;
TheComboBox =  (ComboBox)Page.FindControl(ComboName);

Author

Commented:
I'm trying to use TheComboBox = (ComboBox)Page.FindControl(ComboName);

but it's also not working might be because I'm using a content page.

Author

Commented:
Got it:

TheComboBox = (ComboBox)this.Master.FindControl("ContentPlaceHolder1").FindControl(ComboName);

Explore More ContentExplore courses, solutions, and other research materials related to this topic.