tags:

views:

27

answers:

2

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;
}
+2  A: 

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.

Jon Skeet
I didn't know objects are passed by reference by default
geocine
@geocine: They're not. Objects aren't passed *at all*. References are passed by value though. Please read the article I linked to in the text.
Jon Skeet
@js I am currently reading your article , however checked my update post and please explain why it's working.
geocine
A: 

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

private void PageLoad(object sender, EventArgs e)
{
    txtUserName.Text = "Hello World";
}
Kev
I know that, I want to create a method not only to change text later but inside a class. The one above is just a direct example
geocine