First of all, I am really sorry if the question has been asked somewhere already but I couldn't find an answer anywhere at all after looking. I am fairly new to coding as well so sorry if it isn't actually possible or something.
I have created a windows forms application in c# with multiple panels that themselves contain elements like textboxes and labels. For example, I have a chat panel and a calendar panel. I would like to somehow build access rights into this based on a user's privileges (access levels are stored in a database that is already connected to the application). Ideally, I would like that once the user logs in, the panels are then initialized and created as (from a security point of view) this would be better.
I can't really provide screenshots or much code as it is for an assessed piece of work that I am not allowed to put on the internet.
Thanks so much in advance :)
If i got you right then what you want to do is if(userHasSomePermission) { CreateComponent };
instead of creating it before and if user doesn't have permission disable/hide it
If this is the case it is not much of science but it is bit tricky.
Inside your Form
constructor you have InitializeComponents()
method which is method that is stored in you Form.Designer.cs
file. Inside that file you are creating your controls.
What you can do is create more methods inside your Form.cs
like
private void CreatePanel1()
{
Panel p = new Panel();
p.Location = new Point(3, 3);
p.Size = new Size(50, 50);
p.BackgroundColor = Color.Black;
this.Controls.Add(p);
}
and then inside your constructor call it if needed:
public Form()
{
InitializeComponents();
if( checkIfUserHavePermission )
CreatePanel1();
}
This way components inside our method will be create only if needed.
Tricky part of this is that you will not see components inside designer window
since only components that are located in Form.Designer.cs/InitializeComponents()
are drawn inside it. So any change you want to make will need to be done by hand through code.
Otherwise if you are concerned about security and do not want just to hide/disable some control, you could remove it if needed.
So you could use Tag
property of each control and add let's say Admin_C
to each control's Tag
which is meant only to admins and then do this:
public Form()
{
InitializeComponents();
if(userIsNotAdmin)
{
foreach (Control item in this.Controls)
{
if(item.Tag.ToString() == "Admin_C")
this.Controls.Remove(item);
}
}
}