How do I add a label, or other element dynamically to a windows form panel?

67,358

Solution 1

    //Do I need to call either of the following code to make it do this?
    newLabel.Visible = true;
    newLabel.Show();

is unnecessary.


newLabel.AutoSize = true;

is, most probably, necessary to give it a size.


    panel1.Container.Add(newLabel);

must be replaced by

    newLabel.Parent = panel1;

But, your method should work, unless the drag doesn't work.


Found the bug. It must be panel1.Controls.Add(newLabel); or newLabel.Parent = panel1; instead of panel1.Container.Add(newLabel);. Container is something else.

Solution 2

replace

panel1.Container.Add(newLabel);

by

panel1.Controls.Add(newLabel); 

i think it will add newLabel object to the panel

Share:
67,358
TheJediCowboy
Author by

TheJediCowboy

I like to code...

Updated on July 09, 2022

Comments

  • TheJediCowboy
    TheJediCowboy almost 2 years

    So this is probably a pretty basic question, but I am working with dragging and dropping ListBox Items onto a panel which will create components depending on the value.

    As an easy example, I need it to be able to create a new Label on the panel when an item from the ListBox is dropped onto the panel.

    I have the following code, but am not sure how to dynamically add the Label to the panel once it is dropped.

    Here is my sample code...

    namespace TestApp
    {
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
    
        }
    
        private void Form1_Load(object sender, EventArgs e)
        {
            listBox1.Items.Add("First Name");
            listBox1.Items.Add("Last Name");
            listBox1.Items.Add("Phone");
        }
    
        private void listBox1_MouseDown(object sender, MouseEventArgs e)
        {
            ListBox box = (ListBox)sender;
            String selectedValue = box.Text;
            DoDragDrop(selectedValue.ToString(), DragDropEffects.Copy);
        }
    
        private void panel1_DragEnter(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(DataFormats.Text))
            {
                e.Effect = DragDropEffects.Copy;
            }
            else
            {
                e.Effect = DragDropEffects.None;
            }
        }
    
        private void panel1_DragDrop(object sender, DragEventArgs e)
        {
            Label newLabel = new Label();
            newLabel.Name = "testLabel";
            newLabel.Text = e.Data.GetData(DataFormats.Text).ToString();
    
            //Do I need to call either of the following code to make it do this?
            newLabel.Visible = true;
            newLabel.Show();
    
            panel1.Container.Add(newLabel);
        }
    }
    

    }

  • Tony Abrams
    Tony Abrams over 13 years
    This will add the label to the form as well. If not just blow up from trying to add one control to two parent controls.