我有一个带有选项卡式控件的表单(5个选项卡),在一个选项卡上我有10个图片框,名为pic1,pic,pic3等。在VBA中,可以使用以下内容循环控件:
For i = 1 To 10
Me.Controls("Img" & i).Picture = Me.cboProperty.Column(i)
Next
目前我有
this.pic1.DataBindings.Add("ImageLocation", this.mainTableBindingSource, "localPic1");
this.pic2.DataBindings.Add("ImageLocation", this.mainTableBindingSource, "localPic2");
this.pic3.DataBindings.Add("ImageLocation", this.mainTableBindingSource, "localPic3");
直到10点,但肯定有更好的方法吗?
答案 0 :(得分:4)
就像那样,没有。通常情况下,你会加入一组这样的控件:
foreach (var pictureBox in PictureTab.Controls.OfType(Of PictureBox)())
{
pictureBox.Picture = //...
}
当然,这里的诀窍是没有索引,知道要查看哪一列。但这很容易解决:
int i = 0;
foreach (var pictureBox in PictureTab.Controls.OfType<PictureBox>())
{
pictureBox.Picture = cboProperty.Column[i];
i++;
}
根据您的修改,您可能需要这样:
int i = 0;
foreach(var pictureBox in PictureTab.Controls.OfType<PictureBox>())
{
picutreBox.DataBindings.Add("ImageLocation", mainTableBindingSource, string.Format("loalPic{0}", i));
i++;
}
答案 1 :(得分:2)
也许是这样的:
var pictureBoxes = this.Controls.OfType<PictureBox>().ToList();
for (int i = 0; i < pictureBoxes.Count; i++) {
pictureBoxes[i].DataBindings.Add("ImageLocation",
this.mainTableBindingSource,
"localPic" + (i + 1).ToString());
}
答案 2 :(得分:0)
您可以在表单控件中搜索pictureBox的名称并循环,增加Pic1
,Pic2
等每个的值。
for (int a = 1; a <= 10; a++)
{
string name = "pic" + a;
PictureBox pic = (PictureBox)(this.Controls.Find(name, true))[0];
pic.DataBindings.Add("ImageLocation", this.mainTableBindingSource, "localPic3");
}
答案 3 :(得分:0)
遍历所有表单控件
List<Control> lstOfControls = new List<Contol>();
public void AllPictureControls(Control control, bool enabled)
{
foreach(Control child in control.Controls)
{
if(child.Name.StartsWith("pic"))
{
lstOfControls.Add(control);
}
}
}
答案 4 :(得分:-1)
将所有图片控件的引用放入数据结构中,例如一个数组,并迭代它们。
类似于:
PictureBox[] picBoxArray = new PictureBox[50];
// 50 iterations for 50 object instantiations.
for (int i=0; i<picBoxArray.Length; i++) {
// create an pictureBox instance.
picBoxArray[i] = new PictureBox();
}
PictureBox pb = null;
// 50 iterations for calling methods on each of the 50 objects.
for (int i=0; i<picBoxArray.Length; i++) {
pb = picBoxArray[i];
// do something with the picturebox e.g. pb.SetPicture(...)
}