2013-05-29 59 views
1

我想要一個方法,只能發送窗體的類型打開,然後打開該窗體。打開一個通用表格

這是我到目前爲止有:

private void OpenForm(Type t) 
{ 
    if (OpenedForm != null) 
    { 
     OpenedForm.Close(); 
    } 
     IList list = (IList)Activator.CreateInstance(
     typeof(List<>).MakeGenericType(t)); 
     OpenedForm.MdiParent = this; 
     OpenedForm.Show(); 
     OpenedForm.WindowState = FormWindowState.Maximized; 
} 

我知道我可以做這樣的方法:

private void OpenForm(Form frm) 
{ 
    if (OpenedForm != null) 
    { 
     OpenedForm.Close(); 
    } 
    OpenedForm = frm; 
    OpenedForm.MdiParent = this; 
    OpenedForm.Show(); 
    OpenedForm.WindowState = FormWindowState.Maximized; 
} 

,然後簡單地調用它像這樣:

Form newform = new TestForm(); 
OpenForm(newform); 

但我會有興趣知道是否有可能做到這一點,就像我在第一個代碼片段中試過的一樣,並且需要對ac做些什麼完成這一點。

回答

2
private void OpenForm(Type t) 
{ 
    if(!typeof(Form).IsAssignableFrom(t)) 
     throw new ArgumentException("Required description of Form Type", "t"); 

    if (OpenedForm != null) 
     OpenedForm.Dispose(); //will also close a Form 

    OpenedForm = (Form)Activator.CreateInstance(t); 
    OpenedForm.Show(); 
    OpenedForm.WindowState = FormWindowState.Maximized; 
} 

現在你可以只通過元數據類的FormType或它的派生之一。所以,如果你這樣做:

OpenForm(typeof(Form)); 

一個新的空表格將被創建並打開

+0

非常有趣!謝謝!奇蹟般有效。 – Corne