2010-05-26 23 views
1

我的問題是,我在UserControl中使用TreeView。在調試時,我可以看到結果在TreeView中添加,但是當我將該UserControl用於MainForm時,不會發生這種情況。包含TreeView的UserControl在主應用程序運行時保持空白。我也使用我的主項目引用了UserControl項目。我在這裏給我的代碼來幫助我。UserControl/TreeView問題....在運行時沒有得到結果

在此先感謝。

代碼

在用戶控件類:

public override void Refresh() 
{ 
    PopulateTreeView(); 
} 
private void PopulateTreeView() 
{ 
    TreeNodeCollection treeNodeCollection; 
    treeNodeCollection = CreateParentNode("My Information"); 
    CreateChildNode(treeNodeCollection, "Name"); 
    CreateChildNode(treeNodeCollection, "Address"); 
    this.Update(); 
    myTreeView.ExpandAll(); 
} 
private TreeNodeCollection CreateParentNode(string parentNode) 
{ 
    TreeNode treeNode = new TreeNode(parentNode); 
    myTreeView.Nodes.Add(treeNode); 
    return treeNode.Nodes; 
} 
private void CreateChildNode(TreeNodeCollection nodeCollection, string itemName) 
{ 
    TreeNode treeNode = new TreeNode(itemName); 
    nodeCollection.Add(treeNode); 
} 

在我的MainForm:

private void button1_Click(object sender, EventArgs e) 
{ 
    UserControl userControl = new UserControl(); 
    userControl.Refresh(); 
} 

回答

0

在您創建按鈕的點擊事件一個新的用戶控件,並沒有實際使用用戶放置在您的MainForm上的控件。

要麼你必須在你的MainForm上的UserControl上調用Refresh(),或者你必須將新創建的UserControl添加到MainForm的ControlsCollection中。

當您將UserControl與VisualStudio的Designer一起添加時,MainForm應包含一個名爲userControl1的變量。在這你可以調用Refresh()。然後你應該看到預期的結果和填充的TreeView。

private void button1_Click(object sender, EventArgs e) 
{ 
    userControl1.Refresh(); // Assume that the name of UserControl is userControl1 
} 

如果您想使用一個新的用戶控件每次單擊該按鈕,您必須將控件添加到MainForm的的ControlsCollection。但是你必須執行一些佈局邏輯。

private void button1_Click(object sender, EventArgs e) 
{ 
    UserControl userControl = new UserControl(); 
    userControl.Refresh(); 
    this.Controls.Add(userControl); 
    // Perform layout logic and possibly remove previous added UserControl 
}