开发者

Using a string argument to represent an object

开发者 https://www.devze.com 2023-01-31 09:51 出处:网络
If I have the following code: TextBox txtUsername = new TextBox(); void setEnabled(string str, bool enable)

If I have the following code:

TextBox txtUsername = new TextBox();
void setEnabled(string str, bool enable)
{
    // use str to find the Tex开发者_JS百科tBox object
    // str.Enabled = enable;
}

Is this kinda thing even possible?

I want to be passing in 'Username' and then be prepending it with 'txt'.


For ASP.Net cotrols try Control.FindControl Method

and for winforms use Controls.Find()


Yes, you need to set the Name-Property, then you can access it via it's owner:

this.Controls.Item(str).Enabled = enabled;


One way to do this is to store all your text fields in a dictionary with an identifier:

Dictionary<string,TextBox> index = new Dictionary<string,TextBox>();
index.add("Username",txtUsername);

void setEnabled(string str, bool enable)
{
    index[str].Enabled = enable;
}


You will have to pass the page into the function, otherwise in what context is the function going to search for the control? The you can use Page,FindControl() method to find the control.


Yes,

   TextBox txtUsername = new TextBox();
   txtUsername.Name = "txtUsername ";



  void SetEnable(string str, bool enable)
  {
    this.Controls.Item("txt" + str).Enabled = enabled;
  }

Little modification from "Bobby" answer.

0

精彩评论

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

关注公众号