I have a panel called mainPanel in my Form1 and I want to add controls to it from another class. I tried to set the visibility to public but it didn't work.
This is where I create my controls:
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;
}
Where GetSearchData(SearchWord) is just another function that returns random strings in a list, this function addControlsToMain() belongs to my class SearchFunctions.cs (a class separated from the Form1). I've tried to add these controls doing this:
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);
}
My class CommandFunctions.cs is who has to add these controls. How can I add these list of controls to my panel?
You could go about this a few ways. One of which would be to add a
SearchFunctions
object as a a property to yourForm1
class. Then use that object to call the method that adds the controls.This example uses a button click but you would place that method anywhere you want.