-1

I'm a beginner in C# Windows Forms. I tried to google this but not sure I understand how this is possible. I want to create a Listbox under run time, and succed making one like this:

      private void button3_Click(object sender, EventArgs e)
        {

            ListBox lb = new ListBox();
            
            lb.AllowDrop = true;
            lb.FormattingEnabled = true;
            lb.Size = new System.Drawing.Size(200, 100);
            lb.Location = new System.Drawing.Point(100, 250);

            this.Controls.Add(lb);
        }

But I also need conditions in a function for my listbox, I want to add code in designer to add these too to the listbox. I want to add a function like this for example:


lb.DragEnter += new System.Windows.Forms.DragEventHandler(this.lb_DragEnter);

   and 

 private void lb_DragEnter(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(typeof(System.String)))

                e.Effect = DragDropEffects.Move;
            else
                e.Effect = DragDropEffects.None;
        }

I hope i explain my problem clear!

  • 1
    Are you asking how to subscribe to event in code? That's [very basic stuff](https://learn.microsoft.com/en-us/dotnet/standard/events/#event-handlers). – Sinatr Apr 29 '21 at 12:27
  • Hi, thank you for the link and the feed back. Have a nice day, kind regards – beginnerbeginner Apr 29 '21 at 14:27

1 Answers1

0

welcome to stack.

I might misunderstand what you're trying to do, but couldn't you just add the event in your button3_Click method?

private void button3_Click(object sender, EventArgs e)
{
    ListBox lb = new ListBox();
        
    lb.AllowDrop = true;
    lb.FormattingEnabled = true;
    lb.Size = new System.Drawing.Size(200, 100);
    lb.Location = new System.Drawing.Point(100, 250);

    // Your event
    lb.DragEnter += new System.Windows.Forms.DragEventHandler(this.lb_DragEnter);

    this.Controls.Add(lb);
}


private void lb_DragEnter(object sender, DragEventArgs e)
{
    if (e.Data.GetDataPresent(typeof(System.String)))
        e.Effect = DragDropEffects.Move;
    else
        e.Effect = DragDropEffects.None;
}
Ben
  • 166
  • 2
  • 19
  • Hi, thank you for your fast answer, its working! I tried something similair before but I must have missed something, i got missing reference when i tried. But your solution is working perfect. Thank you very much. – beginnerbeginner Apr 29 '21 at 12:39