My code loops through all the files in a folder then makes a label for them. Before it does though, you need to open the folder using FolderBrowserDialog
. I want to make it so: When there's a folder ALREADY open in the program, I can clear all of those labels so there's room for the new batch of labels.
Code:
foreach(string song in files)
{
Label songLab = new Label();
songLab.Padding = new Padding(6);
songLab.AutoSize = true;
songLab.Location = new Point(prevX 10, prevY 20);
songLab.Click = (o, e2) =>
{
MessageBox.Show("You Clicked " songLab.Text);
};
songLab.MouseEnter = (o, e3) =>
{
Cursor = Cursors.Hand;
songLab.ForeColor = Color.Red;
};
songLab.MouseLeave = (o, e4) =>
{
Cursor = Cursors.Default;
songLab.ForeColor = Color.Black;
};
Controls.Add(songLab);
int fileExtPos = song.LastIndexOf(".");
var songFixd = song.Substring(0, fileExtPos);
prevY = 20;
songLab.Text = songFixd "\n";
}
```
CodePudding user response:
I think you should use groupbox (or a control like that). Add the Labels to the groupbox. like this: groupBox1.Controls.Add(songLab); And delete from groupbox when deleting in bulk. like this: groupBox1.Controls.Clear();
CodePudding user response:
The easiest way is probably to keep a separate list of labels:
myLabels.Add(songLab);
Controls.Add(songLab);
Then you can loop thru it and delete the labels:
foreach(var label in myLabels){
Controls.Remove(label);
}
However, it sounds like you are doing something like a listview or datagrid. Using these might be better than adding labels manually. You could also consider a fully custom control where you manage all the drawing and event-handling yourself rather than relying on existing controls.