Open form with Form Name in winform appliaction

霸气de小男生 提交于 2019-11-28 05:13:11

问题


I want to ask what should i do to open form with the help or class name in winform c#?

I have three different forms

  • UserManagement
  • GroupsManagement
  • LocationManagement

I get permission from database for these three forms

in menu click i fill tag Property with the name of form like this

tsmMain.Tag = item.PermissionName
tsmMain.Click += new EventHandler(tsmMain_Click);

what i want to do is to open form dynamically in button click and to remove these if condition? Can i do this with reflection or else??

ToolStripMenuItem aa = sender as ToolStripMenuItem;
        var tag = aa.Tag;
        if (tag == "User Management")
        {
            UserManagement oUserForm = new UserManagement();
            oUserForm.Show();
        }
        if (tag == "Groups Management")
        {
            GroupManagement oGroupForm = new GroupManagement();
            oGroupForm.Show();
        }

回答1:


You may be able to do something like this, using the name of your form, as a string argument:

var form = (Form)Activator.CreateInstance(Type.GetType("YourNameSpace.UserManagement"));
form.Show();



回答2:


One straightforward, but not necessarily very clean solution would be to store the forms right there in the Tag property of your menu items, rather than the strings.

Somewhere at the beginning of your application, you'd have to assign these instances:

myUserManagementItem.Tag = new UserManagement();
myGroupsManagementItem.Tag = new GroupManagement();

Then, in the click event, you could shorten your code to:

ToolStripMenuItem aa = sender as ToolStripMenuItem;
Form form = aa.Tag as Form;
form.Show();

Cleaner solutions would include the following:

  • Provide separate event handlers for different menu items.
  • Derive your own menu item types that store the form to show in a strongly-typed property.


来源:https://stackoverflow.com/questions/15155024/open-form-with-form-name-in-winform-appliaction

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!