开发者

Reference an ASP control inside a function or class method

开发者 https://www.devze.com 2023-01-19 07:50 出处:网络
How do you reference an asp.net control on your page inside a function or a class. private void PageLoad(object sender, EventArgs e)

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";
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号