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 txtUserN开发者_运维技巧ame, "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;
}
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.
Unless I'm missing something, all you need to do is this:
private void PageLoad(object sender, EventArgs e)
{
txtUserName.Text = "Hello World";
}
精彩评论