Nick
Nick

Reputation: 1102

Changing a form layout in C#

I am working on a program which requires a user to select the file that he/she wishes to open.

There are about 3 different files they can choose from, and each of those files affect the layout of the buttons, and some of their attributes also.

The problem is, at the moment I have this huge list with:

label1.Visible = false;
label2.Visible = false;
form.size = etc.

Each file affects about 16 different controls, so that's a total of 48 possible changes.

Is there a faster/better way to organize the layout of your program?

Thank you in advance.

Framework: 3.5 Language: C#

Windows Forms Application

Upvotes: 1

Views: 3756

Answers (4)

immutabl
immutabl

Reputation: 6903

I'd put each layout in its own Placeholder control (set all of them to be invisible in markup) and add some logic to display the one you want.

(Assuming you're talking about webforms).

Upvotes: 0

Doc Brown
Doc Brown

Reputation: 20044

Brandon suggested grouping with panels, which may be a reasonable solution if your 16 controls lay together in a rectangular area. Another form of grouping can be achieved by giving a group of controls reasonable names and access them by their names at run-time.

I will assume you are using Windows Forms. For example, instead of having 16 lines of code like this

label_1_1.Visible = false;
label_1_2.Visible = false;
//...
label_1_16.Visible = false;

you add this function to your form

Control FindControl(string name)
{
    foreach (Control c in this.Controls)
    {
         if (c.Name == name)
         {
              return c;
         }
     }
     return null;
 }

and use it this way:

 for(int i=1;i<=16++i)
     ((Label)FindControl("label_1_" + i)).Visible=false;

(you should add some error checking, of course)

Upvotes: 1

Mark Rendle
Mark Rendle

Reputation: 9414

If you're building your application using WPF you can use the Visual State Manager to define custom states for the window and set the visibility of controls according to the state. Or you could bind the visibility property on the controls to a property on the ViewModel.

For future reference, C# is the language; you need to specify which framework you're using for your application.

Upvotes: 2

Brandon
Brandon

Reputation: 69973

I would suggest grouping them into Panels and then toggling the visibility on the Panel instead.

Upvotes: 5

Related Questions