简体   繁体   中英

DragDrop button text in C# (WinForm)

My goal is to have multiple buttons whose text can be switched on the screen through dragging the text from one button to another (it's not necessary that the buttons themselves be switched, only the text on them, although if it's easier to switch the buttons themselves, that's fine). I have tried to follow this MSDN article but as soon as I actually begin to drag, I get a "no" symbol (an O with a / through it). Am I missing something? (Code below)

Thanks in advance!

public partial class Form1 : Form
{
    Button button1 = new Button();
    Button button2 = new Button();

    public Form1()
    {
        InitializeComponent();

        button1.Text = "Button 1";
        button2.Text = "Button 2";

        button2.Location = new Point(100, 0);

        this.Controls.Add(button1);
        this.Controls.Add(button2);

        button1.MouseDown += new MouseEventHandler(button_MouseDown);
        button2.MouseDown += new MouseEventHandler(button_MouseDown);

        button1.DragEnter += new DragEventHandler(button_DragEnter);
        button2.DragEnter += new DragEventHandler(button_DragEnter);

        button1.DragDrop += new DragEventHandler(button_DragDrop);
    }

    private void button_MouseDown(object sender, MouseEventArgs e)
    {
        ((Button)sender).DoDragDrop(((Button)sender).Text, DragDropEffects.Move);
    }

    private void button_DragEnter(object sender, DragEventArgs e)
    {
        e.Effect = DragDropEffects.Move;
    }

    private void button_DragDrop(object sender, DragEventArgs e)
    {
        //I'm not sure what goes here, but I can figure that out through experimentation
    }
}

So it turns out I just had to do some more research. Adding button.AllowDrop = true for both buttons solved the issue

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM