Adding dynamic controls to winform not working

I am creating dynamic PictureBox and label in WinForms. For this I have created a method which creates these items on the basis of given integer. In the first run while loading the form, its works smoothly, but when I pass any integer from a dropdown box, it does not make any changes. I tried debugging the code, and all the labels are created accordingly but it is not reflected in the winForm. I tried using Invalidate, Update, Refresh but non of them worked.

Here is the method that I have implemented.

private void createPictureBox(int size) { //this.Controls.Clear(); panel1.Controls.Clear(); Label[] ParameterLabel = new Label[size]; PictureBox[] ParameterBack = new PictureBox[size]; int y_value = 11; this.Refresh(); for (int i = 0; i < size; ++i) { ParameterLabel[i] = new Label(); ParameterLabel[i].Text = "Test Text"; ParameterLabel[i].Font = new System.Drawing.Font("Calibri", 8, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(128))); ParameterLabel[i].ForeColor = System.Drawing.Color.White; ParameterLabel[i].BackColor = System.Drawing.Color.FromArgb(1, 0, 64); ParameterLabel[i].Size = new System.Drawing.Size(145, 20); ParameterLabel[i].Location = new Point(30, y_value); ParameterLabel[i].Anchor = AnchorStyles.Left; ParameterLabel[i].Visible = true; ParameterBack[i] = new PictureBox(); ParameterBack[i].Image = Image.FromFile(STR_SETTING_PATH + "\\" + STR_IDEA_NO_XXXXX + "_01_nv.png"); ParameterBack[i].Size = new System.Drawing.Size(400, 32); ParameterBack[i].Location = new Point(2, y_value - 10); ParameterBack[i].Anchor = AnchorStyles.Left; ParameterBack[i].Visible = true; //this.Controls.Add(ParameterBack[i]); y_value += 37; } panel1.Controls.AddRange(ParameterLabel); panel1.Controls.AddRange(ParameterBack); panel1.Invalidate(); }

-------------Problems Reply------------

Who can you distinguish between controls created in the first call and those created in other calls? I've tested your function with a tiny change, it seems to be working fine:

int CallIndex = 0; // this is on the form level

private void button1_Click(object sender, EventArgs e)
CallIndex += 1;

private void createPictureBox(int size)
// this has the exact same code as your method (copy-paste into my visual studio),
// except this change:
// ParameterLabel[i].Text = "Test Text";
ParameterLabel[i].Text = string.Format("Test {0}", CallIndex); // instead of the row above

I did remove the previously added controls and added the new one after which apparently solved my problem. The problem was due to piling of Controls one over another. I first removed the previously created controls using


Then re-created its instance, which solved my problem.

Category:c# Views:1 Time:2018-02-09

Related post

Copyright (C), All Rights Reserved.

processed in 0.333 (s). 11 q(s)