'How to check if dynamic checkbox are checked
I've an application to import some pictures from a folder into another. I use picturebox to show my pictures and have a checkbox next to it. If it's unchecked i dont wanna import them.
So here is my code for creating a checkbox :
public void CreateCheckBox(Form formInstance,int yLocation, int xLocation, int iNumber)
{
CheckBox box = new CheckBox();
box.Name = "cbxName" + iNumber.ToString();
box.Location = new Point(xLocation+40,yLocation+90);
box.Visible = true;
box.Enabled = true;
box.Checked = true;
box.CheckedChanged += new EventHandler(cbx_CheckedChange);
formInstance.Controls.Add(box);
}
And my pictureBox :
public void CreatePictureBox(Form formInstance,int iNumber)
{
string[] tNomImage = RecupererNomImage();
PictureBox pbxImage = new PictureBox();
pbxImage.Name = "pbxName" + iNumber.ToString();
pbxImage.Image = Image.FromFile(tNomImage[iNumber]);
pbxImage.Width = 90;
pbxImage.Height = 90;
pbxImage.Location = new Point(iXLocation, iYLocation);
pbxImage.Visible = true;
pbxImage.BorderStyle = BorderStyle.FixedSingle;
pbxImage.SizeMode = PictureBoxSizeMode.Zoom;
formInstance.Controls.Add(pbxImage);
pbxImage.Enabled = false;
CreateCheckBox(this, iYLocation, iXLocation, iNumber);
if (iXLocation+iXSpacing*2 > this.Width)
{
iXLocation = XLOCATION;
iYLocation += iXSpacing;
}
else
{
iXLocation += iXSpacing;
}
And I wanna know which checkbox is checked so I can export the picture next to it.
Solution 1:[1]
Change your methods so that they RETURN the control that was created:
public CheckBox CreateCheckBox(Form formInstance,int yLocation, int xLocation, int iNumber)
{
// ... existing code ...
return box;
}
Now you can store a reference to that CheckBox in the Tag() property of the PictureBox:
public PictureBox CreatePictureBox(Form formInstance,int iNumber)
{
// ... existing code ...
CheckBox cb = CreateCheckBox(this, iYLocation, iXLocation, iNumber);
pbxImage.Tag = cb;
// ... existing code ...
return pbxImage;
}
Finally, add all of those returned PictureBoxes to a List<PictureBox> so you can easily reference and iterate over them. Simply cast the control stored in the Tag() property back to a CheckBox and you can determine if each PictureBox should be imported or not.
Solution 2:[2]
List<CheckBox> c = Controls.OfType<CheckBox>().Cast<CheckBox>().ToList();
forech(CheckBox item in c){
if(c.checked){
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Idle_Mind |
| Solution 2 | Salim Baskoy |
