Click here to Skip to main content
15,881,882 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I am creating a WinForm application, in which I have a TabControl1 and at run time created TabPage and PictureBox.

On a Button Click, I make new tab page and PictureBox and add them to the TabControl1.

Now, I can change image of only last created PictureBox.
and when I try to change the image of any PictureBox, except the last one, I am not able to do that

This is the code example.

button1 creates new TabPage and PictureBox.
C#
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 changes image of PictureBox.
C#
private void button2_Click(object sender, EventArgs e)
{
    picturebox1.Image = WindowsFormsApplication7.Properties.Resources.logo2;
}



[Edit member="Tadit"]
Corrected formatting and grammatical issues.
[/Edit]
Posted
v2
Comments
[no name] 18-Sep-13 7:09am    
Probably because you only have one picturebox, picturebox1.
Code Mirror 18-Sep-13 7:19am    
so what should i do? how to create many pictureboxes at runtime
[no name] 18-Sep-13 8:41am    
"what should i do?", how would you expect me to know that? What I would probably do is use an array or list to hold references to the my picture boxes, depending on what I was actually trying to accomplish. Of course, I would probably not do this at all and I would have create a composite control to do this to begin with.

1 solution

pictureBox1 holds the reference to the last created one, that's the problem.
C#
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; 
}

Found Here - only last dynamically created picturebox is accessible[^]


[Edit member="Tadit"]
Link text added to reflect the article title.
Corrected formatting and grammatical issues.
[/Edit]
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900