title: C# Drag and Drop text within a RichTextBox
body: <p>I have a C# project in which I want the user to be able to drag and drop text (<em>i.e.</em> to move text) <strong>within</strong> a RichTextBox  in a WinForm. </p>
  
  <p>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. </p>
  
  <p>How should I do this ?</p>
  
  <p>Below is my non-working attempt sofar.</p>
  
  <pre><code>public partial class Form1 : Form {
      public Form1() {
          InitializeComponent();
          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;
          else
              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 +
             e.Data.GetData(DataFormats.Text).ToString();
          richTextBox1.Text = richTextBox1.Text + s;
      }
  }
  </code></pre>