0

我正在创建一个 win 表单应用程序,其中我有一个tabcontrol1,并在运行时创建了标签页和图片框

在一个按钮上单击创建新的标签页和图片框并将它们添加到 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);          
    }

button2 更改图片框的图像

private void button2_Click(object sender, EventArgs e)
    { 
        picturebox1.Image = WindowsFormsApplication7.Properties.Resources.logo2; 
    }
4

2 回答 2

0

这是因为您总是在创建一个新的图片框来覆盖变量图片框1,因此失去了对除了最后一个创建的图片框之外的所有图片框的引用。

如果单击 button2,则必须转到当前活动的选项卡并在选项卡页控件集合中搜索图片框并在那里更改图像。结果(未优化)应如下所示:

    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; 
        }
于 2013-09-18T11:23:57.303 回答
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一些tabPagetabControl1试试这个:

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; 
    }
}
于 2013-09-18T11:24:12.460 回答