Aivan Monceller
Aivan Monceller

Reputation: 4670

Reference an ASP control inside a function or class method

How do you reference an asp.net control on your page inside a function or a class.

private void PageLoad(object sender, EventArgs e)
{
   //An example control from my page is txtUserName
   ChangeText(ref txtUserName, "Hello World");
} 

private void ChangeText(ref HtmlGenericControl control, string text)
{
   control.InnerText = text;
}

Will this actually change the text of the txtUserName control?

I tried this and is working

private void PageLoad(object sender, EventArgs e)
{
   ChangeText(txtUserName, "Hello World");
} 

private void ChangeText(TextBox control, string text)
{
   control.Text = text;
}

Upvotes: 1

Views: 943

Answers (2)

Kev
Kev

Reputation: 119806

Unless I'm missing something, all you need to do is this:

private void PageLoad(object sender, EventArgs e)
{
    txtUserName.Text = "Hello World";
}

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1500525

Yes, it should, assuming it's at the appropriate point in the page lifecycle, so that nothing else messes with it afterwards. (I don't know the details of ASP.NET lifecycles.

However, it's worth mentioning that there's absolutely no reason to pass it by reference here. It suggests that you don't fully understand parameter passing in .NET - I suggest you read my article on it - once you understand that (and the reference/value type distinction) all kinds of things may become easier for you.

Of course, if you've already tried the code given in the question and found it didn't work, please give more details. Depending on the type of txtUserName, it could even be that with ref it won't compile, but without ref it will just work.

Upvotes: 2

Related Questions