I have a main form with a menu that contains lots of items which in turn open different forms. Currently I do the following to open a particular form:
if (canShowCustomerForm)
new CustomerForm().ShowDialog(this);
else
{
MessageBox.Show("You don't have enough rights to view this form.");
}
Is there a way to move this code in a class and then passing the form type and boolean parameter instead of repeating the code for each and every menu item?
public static class FormHelper
{
public static DisplayResult ShowForm<T>(IWin32Window owner, bool canShowForm)
where T : Form, new()
{
if (canShowForm)
{
using (T form = new T())
{
return form.ShowDialog(owner);
}
}
else
{
MessageBox.Show("You don't have enough rights to view this form.");
}
}
}
Rather than writing the same logic over and over again you can extract it into a function like below:
void ShowFormIfAllowed<TForm>(bool allowed) where TForm : Form, new() {
if (allowed) {
using (var form = new TForm()) {
form.ShowDialog(this);
}
}
else {
MessageBox.Show("You don't have enough rights to view this form.");
}
}
Then in your menu handling you can call it like:
ShowFormIfAllowed<CustomerForm>(canShowCustomerForm);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.