[英]Add controls dynamically from another class C#
我的Form1中有一個名為mainPanel的面板,我想從另一個類向其添加控件。 我試圖將公開性設置為公開,但沒有成功。
這是我創建控件的地方:
public List<Control> addControlsToMain(string SearchWord, Size ContainerSize)
{
List<Control> ListOfControls = new List<Control>();
Panel Box;
Label Title, Content;
int PositionCounter = 10;
foreach (string data in GetSearchData(SearchWord))
{
Box = new Panel();
Title = new Label();
Content = new Label();
Box.Size = new Size((int)(ContainerSize.Width * 0.8), 100);
Title.Size = new Size(Box.Width, 20);
Content.Size = new Size((int)(Box.Width * 0.8), 60);
Box.Location = new Point(10, PositionCounter);
Title.Location = new Point(25, 10);
Content.Location = new Point(25, 40);
Title.Text = "Title";
Content.Text = "Content here";
ListOfControls.Add(Box);
Box.Controls.Add(Title);
Box.Controls.Add(Content);
PositionCounter += 110;
}
return ListOfControls;
}
其中GetSearchData(SearchWord)只是另一個返回列表中隨機字符串的函數,此函數addControlsToMain()屬於我的類SearchFunctions.cs(與Form1分離的類)。 我試圖添加這些控件來做到這一點:
var mainForm = new Form1();
SearchFunctions src = new SearchFunctions();
System.Drawing.Size panelSize = mainForm.mainPanel.Size;
foreach(System.Windows.Forms.Control data in src.addControlsToMain("Stack overflow", panelSize))
{
mainForm.mainPanel.Controls.Add(data);
}
我的類CommandFunctions.cs是必須添加這些控件的人。 如何將這些控件列表添加到面板中?
您可以通過幾種方法進行處理。 一種方法是將SearchFunctions
對象作為屬性添加到Form1
類。 然后使用該對象調用添加控件的方法。
public partial class Form1 : Form
{
SearchFunctions src = new SearchFunctions();
public void Button_Click(object sender, EventArgs e)
{
List<Control> myControls = src.addControlsToMain(mySearchWord, mySize);
foreach (Control c in myControls)
{
this.Controls.Add(c);
}
}
}
本示例使用按鈕單擊,但是您可以將該方法放置在所需的任何位置。
問題很可能在這里:
var mainForm = new Form1();
您正在創建一個永遠不會顯示的Form1新實例。
以下是一些選項:
要么
addControlsToMain()
函數,因此您可以使用this
控件添加控件,就像Juken在他的帖子中演示的那樣。 要么
================================================== ======================
腳步:
1.利用適當的名稱空間來調用控件類實用工具,例如:System.Web.UI.Web Controls(以我為例)
2.在Main.cs中
Panel Panel1= new Panel();
foreach(some condition)
{
class1.addControlsToMain("xyz_Searchword", 2, ref Panel1); //Calls the method which creates the controls
}
Class1.cs
{ Public static void addControlsToMain(string searchword, int size,ref Panel p1) { List<WebControl> list = new List<WebControl>(); //should be List<Control> for Windows Label lb1, title; lb1 = new Label(); title = new Label(); lb1.Text = "Test Label Control1"; title.Text = "Test Title Label Control"; p1.Controls.Add(lb1); p1.Controls.Add(title); list.Add(p1); } }
長話短說,請嘗試使用Ref關鍵字。 希望這會有所幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.