开发者

Dynamically Accessing ASP.NET Controls based on variables...is it possible?

开发者 https://www.devze.com 2023-04-12 15:51 出处:网络
I have been tasked in re-factoring some code on a web forms project and there is one section of code that I think could be combined into a single method and then passed a int and would modified the co

I have been tasked in re-factoring some code on a web forms project and there is one section of code that I think could be combined into a single method and then passed a int and would modified the controls based on that. Here is the code:

txtline1_amnestyCheck.Text = "Y";
txtline1_range.BackColor = System.Drawing.Color.Azure;
txtline1_amnt.BackColor = System.Drawing.Color.Azure;
txtline1_minreqmet.BackColor = System.Drawing.Color.Azure;
txtline1_elizperdt.BackColor = System.Drawing.Color.Azure;
txtline1_amnestyCheck.BackColor = System.Drawing.Color.Azure;
txtline1_afterNSFamnt.BackColor = System.Drawing.Color.Azure;
txtline1_NSFamnt.BackColor = System.Drawing.Color.Azure;

There are twelve different fields sections of this ranging from txtline1 through txtline12. My hopes is to make this a single method that looks something like this:

private void ChangeTextlines(int i)
{
    txtlinei_amnestyCheck.Text = "Y";
    txtlinei_range.BackColor = System.D开发者_如何学Crawing.Color.Azure;
    txtlinei_amnt.BackColor = System.Drawing.Color.Azure;
    txtlinei_minreqmet.BackColor = System.Drawing.Color.Azure;
    txtlinei_elizperdt.BackColor = System.Drawing.Color.Azure;
    txtlinei_amnestyCheck.BackColor = System.Drawing.Color.Azure;
    txtlinei_afterNSFamnt.BackColor = System.Drawing.Color.Azure;
    txtlinei_NSFamnt.BackColor = System.Drawing.Color.Azure;
}

Where i would be the line number that is changing. Now is there a way for me to be able to do this or am I stuck with the 96 lines of code of having a group for each txtline?


If you know the parent control where they all sit then you could use it's FindControl method to access each one.

var myControl = (ControlType)ParentControl.FindControl("txtline" + i + "_anestyCheck");


If you're attempting to apply a common goal to a specific kind of control, you could accomplish this by looping through the controls on your form. This page has a good example of how to loop from the top down. e.g.

... // Control Loop (see linked site)

if (control is Label)
{
    Label label = (Label)control;
    label.BackColor = System.Drawing.Color.Azure
}

This way you don't need to identify each control by it's name, but rather a type of control you are attempting to set. If you know all of your controls are in a panel you've defined, then you can loop through the of the controls on that panel looking for a specific type to set.

0

精彩评论

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