3

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();
        }
4

2 に答える 2

8

フォームの名前を文字列引数として使用すると、次のようなことができる場合があります。

var form = (Form)Activator.CreateInstance(Type.GetType("YourNameSpace.UserManagement"));
form.Show();
于 2013-03-01T10:09:35.800 に答える
5

簡単ではありますが、必ずしもきれいではない解決策の 1 つTagは、文字列ではなく、メニュー項目のプロパティにフォームを保存することです。

アプリケーションの最初のどこかで、これらのインスタンスを割り当てる必要があります。

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

次に、クリック イベントで、コードを次のように短縮できます。

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

よりクリーンなソリューションには、次のものが含まれます。

  • メニュー項目ごとに個別のイベント ハンドラーを提供します。
  • 厳密に型指定されたプロパティに表示するフォームを格納する独自のメニュー項目タイプを派生させます。
于 2013-03-01T10:07:06.623 に答える