Go through components of form C #

0

Hello, I have a table coming from the database, with several rows and columns. One of these columns is stored the address of the previously saved image. Now I need to go through all the PictureBox and put in the ImageLocation the address of those image. Ah yes! Before I forget I have 10 PictureBox in form. I'm using the following code:

foreach (Control item in this.Controls)  
{  
if (item is PictureBox)
{
item.Name.ToString();//Até aqui tudo certo, consigo ver nome dele, mas preciso pegar nome e a propriedade ImageLocation 
}

Does anyone have an idea?

    
asked by anonymous 28.03.2015 / 18:58

2 answers

0

I'll suggest the following:

  • Create the PictureBox dynamically, instead of adding them one by one by the designer:

    public partial class Form1 : Form
    {
        private PictureBox[] pictures;
    
        public Form1()
        {
            InitializeComponent();
    
            // criando as 10 PictureBox de que necessita
            this.pictures = Enumerable.Range(1, 10)
                .Select(this.CriarPictureBox)
                .ToArray();
    
            // eu estou adicionando dentro de um FlowLayout, mas poderia ser no Form,
            // ou dentro de qualquer outro contêiner de sua escolha
            this.flowLayoutPanel1.Controls.AddRange(this.pictures);
        }
    
        private PictureBox CriarPictureBox(int i)
        {
            return new PictureBox
            {
                Name = "pic" + i,
                Location = new Point(0, 0),
                Size = new Size(100, 100),
                BackColor = Color.Black,
                Visible = true,
            };
        }
    }
    
  • With the PictureBox in an array, you can now refer to them using a numeric index inside the loading loop that reads the DataTable. Example:

    private void CarregarImagens(DataTable tabela, int primeiraRow)
    {
        for (int itPic = 0; itPic < this.pictures.Length; itPic++)
        {
            this.pictures[itPic].ImageLocation =
                tabela.Rows[itPic + primeiraRow]["NomeColuna"].ToString();
        }
    }
    
  • 28.03.2015 / 22:22
    0

    He came here unanswered. See how I solved my problem.

    //Primeiro percorri as colunas do datatable;
    for (int i = 0; i < Tabela.Rows.Count; i++)
    {
    //Garanti que as células não estejam vazias
    Celula = Tabela.Rows[i][0].ToString();
    if (Celula != "")
    {
    //Usei um switch para analisar a variável i do for
    switch (i)
    {
    case 0:
    PictureBox1.ImageLocation = Tabela.Rows[i][0].ToString();
    break;
    case 1:
    ptb2lugar.ImageLocation = Tabela.Rows[i]0].ToString();
    break;
    case2:
    ptb3lugar.ImageLocation = Tabela.Rows[i][0].ToString();
    break;
    case 3:
    PictureBox2.ImageLocation = Tabela.Rows[i][0].ToString();
    break;
    }
    }
    }
    
        
    28.03.2015 / 20:50