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);
}
}
}
//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;
Found the bug. It must be panel1.Controls.Add(newLabel);
or newLabel.Parent = panel1;
instead of panel1.Container.Add(newLabel);
. Container
is something else.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With