M. Page M. Page - 1 year ago 233
C# Question

C# Drag and Drop text within a RichTextBox

I have a C# project in which I want the user to be able to drag and drop text (i.e. to move text) within a RichTextBox in a WinForm.

I have found many examples showing how to do drop something onto a RichTextBox but I didn't succeed to have them work when the RichTextBox is both the drag source and drop target.

How should I do this ?

Below is my non-working attempt sofar.

public partial class Form1 : Form {
public Form1() {
this.richTextBox1.AllowDrop = true;
this.richTextBox1.DragEnter += new System.Windows.Forms.DragEventHandler(this.richTextBox1_DragEnter);
this.richTextBox1.DragDrop += new System.Windows.Forms.DragEventHandler(this.richTextBox1_DragDrop);

private void richTextBox1_DragEnter(object sender, System.Windows.Forms.DragEventArgs e) {
if (e.Data.GetDataPresent(DataFormats.Rtf))
e.Effect = DragDropEffects.Move;
e.Effect = DragDropEffects.None;
private void richTextBox1_DragDrop(object sender, System.Windows.Forms.DragEventArgs e) {
int i;
String s;

i = richTextBox1.SelectionStart;
s = richTextBox1.Text.Substring(i);
richTextBox1.Text = richTextBox1.Text.Substring(0, i);

richTextBox1.Text = richTextBox1.Text +
richTextBox1.Text = richTextBox1.Text + s;

Answer Source

Well, I found myself a solution to this problem :

public partial class Form1 : Form {
    public Form1() {
        richTextBox1.EnableAutoDragDrop = true;

And nothing more.

My first attempt was based on MSDN documentation: http://msdn.microsoft.com/en-us/library/aa984395(v=vs.71).aspx, but it seems broken.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download