Reputation: 41
I'm creating a program that does a search for music albums from a fixed source, and returns a list of results as a JSON. I've successfully learnt to deserialise this object so it's usable in C#, but there's one thing I'm struggling with.
At the moment, I've manually created several picture boxes (for album art) and labels (for info.) for results, however the number of results is bound to vary depending on the users search.
Is there a way to perhaps do a 'for each
' loop that goes through each of the results, and can programmatically create the necessary picture box and label combos, in order to cater for fewer or more results?
I ask because I've seen applications perform a search and surely all of the results cannot just be filling preset labels/text boxes?
for each result in results:
{
Create Picture Box;
Create Labels;
}
Upvotes: 2
Views: 1305
Reputation: 30813
Yes, you could to that. Assuming that your code is in a WinForm
Form
, use PictureBox
, Label
, and Controls.Add
:
foreach (var result in results){
PictureBox pb = ...;
//initialize your PictureBox
pb.Location = ...;
pb.Image = ...;
pb.Name = ...;
// etc, then add
Controls.Add(pb);
//similarly for Label
Label lbl = ...;
//initialize your Label
lbl.Location = ...;
lbl.Text = ...;
lbl.Name = ...;
// etc, then add
Controls.Add(lbl);
}
One part you need to be careful in the dynamic creation is the Location
. Make sure that the new controls' locations are not overlapped. If not, they may look like single control, because multiple controls are placed on top of one another.
Note: to do it more systematically, either putting the PictureBox
and Label
in a FlowLayoutPanel
, and/or creating UserControl
with a PictureBox
and a Label
on it would be a great idea. Then we only need to add the UserControl
one by one, either directly to the Form
or to the FlowLayoutPanel
(please read the comments below this answer). My answer is a simplistic approach though, just to point out the idea that: yes, it is possibile to create dynamic controls in C# WinForm
.
Upvotes: 1