Welcome to WindowsClient.net | Sign in | Join

Here are some frequently asked questions about Windows Forms and their answers.

Windows Forms FAQs

How do I support drag and drop for a RichTextBox?

You must set the AllowDrop property on the RichTextBox control to true, and also handle both the DragEnter and DragDrop events.

Add event handlers to the control:

[C#]

using System.Windows.Forms;

richTextBox1.DragEnter += new DragEventHandler( richTextBox1_DragEnter );
richTextBox1.DragDrop += new DragEventHandler( richTextBox1_DragDrop );

[Visual Basic]

Imports System.Windows.Forms;

AddHandler Me.richTextBox1.DragEnter, _
  New DragEventHandler(AddressOf Me.richTextBox1_DragEnter)
AddHandler Me.richTextBox1.DragDrop, _
  New DragEventHandler(AddressOf Me.richTextBox1_DragEnter)

Write event handlers:

[C#]

private void richTextBox1_DragEnter( object sender, DragEventArgs e )
{
  e.Effect = e.Data.GetDataPresent( DataFormats.Text )
    ? DragDropEffects.Copy
    : DragDropEffects.None;
}

private void richTextBox1_DragDrop( object sender, DragEventArgs e )
{
  // Load the file into the control
  string text = (string) e.Data.GetData( "Text" );
  richTextBox1.LoadFile( text, RichTextBoxStreamType.RichText );
}

[Visual Basic]

Private Sub richTextBox1_DragEnter(sender As Object, e As DragEventArgs)
  If CType(e, DragEventArgs).Data.GetDataPresent(DataFormats.Text) Then
  e.Effect = DragDropEffects.Copy
  Else
    e.Effect = DragDropEffects.None
  End If
End Sub

Private Sub richTextBox1_DragDrop(sender As Object, e As DragEventArgs)
  ' Loads the file into the control
  richTextBox1.LoadFile(e.GetData("Text"), [String]), _
    RichTextBoxStreamType.RichText)
End Sub

Contributed from George Shepherd's Windows Forms FAQ



Page view counter