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.
CodePudding user response:
I presume a picturebox will have a name like:
pbxName141
And its matching checkbox will have a name like:
cbxName141
You can ask the form for all the checked boxes:
var cbs = formInstance.Controls.OfType<CheckBox>().Where(cb => cb.Checked);
You can convert the checkbox name into the related picturebox name and look up the picturebox by name:
foreach(var cb in cbs){
var pbName = "p" cb.Name.Substring(1);
var pb = formInstance.Controls[pbName];
}
So many ways to skin this cat..
CodePudding user response:
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.
CodePudding user response:
List<CheckBox> c = Controls.OfType<CheckBox>().Cast<CheckBox>().ToList();
forech(CheckBox item in c){
if(c.checked){
}
}