2013-11-15 32 views
1

大家好,我慢慢學習C#的可見性,我有這樣的問題:使用變量的值設置面板

我要作出這樣的規定所有的面板不可見的功能,然後設置一個就像從字符串變量中看到的那樣。

public void setMeVisible(string PanelName) 
{ 
    PageMainScreen.Visible = false; 

    PageNewRegistration.Visible = false; 

    PageSelectedPatient.Visible = false; 

    ["PanelName"].Visible = true; // in this line I want to set the value of 
    // PanelName.Visible=true. 
    // what is the format that I must put PanelName? 
} 
+1

windows還是web? – Liam

+0

幸運的是在C#中沒有eval:D – giammin

+2

[windows解決方案](http://stackoverflow.com/questions/1536739/c-sharp-get-control-by-name) – Liam

回答

2

使用Page.FindControl用於ASP.Net:

var control = FindControl(PanelName); 
if (control != null) 
    control.Visible = true; 

如果控件嵌套,您可以通過this answer創建FindControlRecursive功能,建議:

private Control FindControlRecursive(Control root, string id) 
{ 
    return root.ID == id 
       ? root 
       : (root.Controls.Cast<Control>() 
        .Select(c => FindControlRecursive(c, id))) 
        .FirstOrDefault(t => t != null); 
} 

然後調用它在做:

var control = FindControlRecursive(form1, PanelName); // Or another top-level control other than form1 
if (control != null) 
    control.Visible = true; 

使用Controls.Find Windows窗體應用程序:

var control = Controls.Find(PanelName, true).FirstOrDefault(); 
if (control != null) 
    control.Visible = true; 
3

對於Windows,最簡單的方法是遍歷所有控件並檢查它是否爲面板並將其設置爲false。在同一個循環中,您可以在「PanelName」中檢查傳遞的panel.Name並將其設置爲true。事情是這樣的

foreach(Control control in form.Controls) 
{ 
    if(control is Panel) 
    { 
     control.Visible = false; 
     if(control.Name == "PanelName") 
      control.Visible = true; 

    } 
} 
+2

如果上述面板嵌套在一個容器**其他**而不是表格中?......如果它們全部放在不同的容器中怎麼辦?那麼你需要**遞歸**搜索。 –

+0

它只是一個示例代碼來指導答案。 – appcoder

1

循環,並找到控制是不是真的有必要。您應該所有的面板添加到同一容器中,用Controls收集和傳遞之名,以獲得控制:

public void setMeVisible(string PanelName) { 
    PageMainScreen.Visible = false; 
    PageNewRegistration.Visible = false; 
    PageSelectedPatient.Visible = false; 
    Control c = sameContainer.Controls[PanelName]; 
    if(c != null) c.Visible = true; 
} 

如果每次只有1面板可見,你應該使用一些變量來跟蹤當前顯示面板和隱藏只(而不是因爲你做了所有的控件)這是這樣的:

Control currentShown; 
public void setMeVisible(string PanelName) { 
    Control c = sameContainer.Controls[PanelName]; 
    if(c != null) { 
    c.Visible = true; 
    if(currentShown != null) currentShown.Visible = false; 
    currentShown = c; 
    } 
} 

而最後,如果你不想使用相同的容器您的所有面板。你應該申報一些List<Panel>包含所有的面板,那麼你可以通過它們方便地瀏覽:

List<Panel> panels = new List<Panel>(); 
panels.AddRange(new[]{PageMainScreen, PageNewRegistration, PageSelectedPatient}); 
public void setMeVisible(string PanelName) { 
    var c = panels.FirstOrDefault(panel=>panel.Name == PanelName); 
    if(c != null) { 
    c.Visible = true; 
    if(currentShown != null) currentShown.Visible = false; 
    currentShown = c; 
    }  
} 

注意:不要嘗試你的用戶界面不必要地複雜。我想表示您應將所有面板放在同一個容器(如您的表單)上。這就是我們的方式,這樣你就可以使用第一種方法,不需要循環,易於維護。您還應該考慮DockBringToFront()SendToBack()等方法來顯示/隱藏視圖。