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);
}
}
}
//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.
replace
panel1.Container.Add(newLabel);
by
panel1.Controls.Add(newLabel);
i think it will add newLabel object to the panel
I think Visible is set to True by default, but it's very possible you need to refresh the panel after adding the label in order to see the label.
I believe you'll still need to add the label to the form's ControlCollection
for it to render. So add something like the following to the end of the DragDrop
method:
this.Controls.Add(newLabel);
精彩评论