我正在创建一个win form应用程序,其中我有 tabcontrol1 , 并在运行时创建了tabpage和picturebox
点击按钮我创建新标签页和图片框 并将它们添加到tabcontrol1。
现在我可以更改仅限上次创建图片框的图片... 当我尝试更改除最后一个之外的任何图片框的图像时,我无法做到这一点
这是代码示例
button1创建新的标签页和图片框
private void button1_Click(object sender, EventArgs e)
{
TabPage tpgallery = new TabPage();
tpgallery.Name = "tpgallery";
tpgallery.Text = " Gallery ";
tabControl1.TabPages.Add(tpgallery);
picturebox1 = new PictureBox();
picturebox1.Name = "picturebox1name";
picturebox1.Image = WindowsFormsApplication7.Properties.Resources.logo1;
tpgallery.Controls.Add(picturebox1);
}
按钮2更改图片框的图像
private void button2_Click(object sender, EventArgs e)
{
picturebox1.Image = WindowsFormsApplication7.Properties.Resources.logo2;
}
答案 0 :(得分:0)
这是因为你总是创建一个新的图片框,覆盖变量picturebox1,因此放弃了对除最后一个图片框之外的所有图片框的引用。
如果单击button2,则必须转到当前活动的选项卡并在tabpages控件集合中搜索图片框并在那里更改图像。 结果(未优化)应如下所示:
private void button2_Click(object sender, EventArgs e)
{
PictureBox pb = null;
foreach (Control c in tabControl1.SelectedTab.Controls)
if (c is PictureBox)
{
pb = c as PictureBox;
break;
}
pb.Image = WindowsFormsApplication7.Properties.Resources.logo2;
}
答案 1 :(得分:0)
pictureBox1
保存对最后创建的引用,这是你的问题。试试这个:
private void button2_Click(object sender, EventArgs e)
{
PictureBox pb = tabControl1.SelectedTab.Controls.OfType<PictureBox>()
.FirstOrDefault(p=>p.Name == "picturebox1name");
if(pb != null)
pb.Image = WindowsFormsApplication7.Properties.Resources.logo2;
}
注意:您也可以使用此代码获取图片框:
PictureBox pb = tabControl1.SelectedTab.Controls["picturebox1name"] as PictureBox;
如果您tabControl2
tabPage
tabControl1
private void button2_Click(object sender, EventArgs e)
{
TabControl actualTabControl = tabControl1.SelectedTab.Controls.OfType<TabControl>()
.FirstOrDefault();
if(actualTabControl != null){
PictureBox pb = actualTabControl.SelectedTab.Controls["picturebox1name"] as PictureBox;
if(pb != null)
pb.Image = WindowsFormsApplication7.Properties.Resources.logo2;
}
}
,请尝试以下操作:
{{1}}