1 Comments
  •   Posted in: 
  • C#

I stepped trough several lines of code towards a line where a bug occurred and encountered a horrible line of code. I had doubts if I should share it. It is really bad and unreliable. But I will share it so that other developers will never make this mistake.

int step = ((Wizard)Page.Controls[0].Controls[3].Controls[7].Controls[1].Controls[1]).ActiveStepIndex;

Believe it or not, this has worked for several years! It was used inside a usercontrol to access a parameter of a control on the page which contains the usercontrol.

Why I love refactoring

You will see why when you look at the code. I have made a public property on the page which has the wizard control and the usercontrol.

public int Step
{
    get { return CheckoutWizard.ActiveStepIndex; }
}

In the code behind of the usercontrol, you only need one line to get the current index of the wizard control:

int step = ((Page_Checkout)Page).Step;

And that’s it! This is the best way to access a property of a control on the page which holds the usercontrol. By the way, you can also give the usercontrol a property and fill it from within the page.

The world is a better place now with this refactored line.

Good luck coding!

and yes, you can always flattr me.

kick it on DotNetKicks.com Shout it

Post on LinkedIn