Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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);
    }
}

}

like image 527
TheJediCowboy Avatar asked Jan 17 '11 18:01

TheJediCowboy


1 Answers

    //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.

like image 135
Vercas Avatar answered Oct 11 '22 12:10

Vercas