Reputation:
How do i drag files or folders into a textbox? i want to put the foldername in that very textbox. C# .NET
Upvotes: 7
Views: 16530
Reputation: 53
If you get the Error Messages below, This applied to me when using Visual Studio 2015, try e.Effect instead of e.Effects
Severity Code Description Project File Line Suppression State Error CS1061 'DragEventArgs' does not contain a definition for 'Effects' and no extension method 'Effects' accepting a first argument of type 'DragEventArgs' could be found (are you missing a using directive or an assembly reference?)
Upvotes: 0
Reputation: 136391
i wrote this code based in this link
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
textBox1.AllowDrop = true;
textBox1.DragEnter += new DragEventHandler(textBox1_DragEnter);
textBox1.DragDrop += new DragEventHandler(textBox1_DragDrop);
}
private void textBox1_DragEnter(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.FileDrop))
e.Effects = DragDropEffects.Copy;
else
e.Effects = DragDropEffects.None;
}
private void textBox1_DragDrop(object sender, DragEventArgs e)
{
string[] FileList = (string[])e.Data.GetData(DataFormats.FileDrop, false);
string s="";
foreach (string File in FileList)
s = s+ " "+ File ;
textBox1.Text = s;
}
}
Upvotes: 17
Reputation: 60927
CodeProject has a really nice example of doing this, including how to enable drag and drop both ways (from Explorer to your app, and from your app to Explorer).
Upvotes: 1
Reputation: 292355
Set AllowDrop to true on your TextBox, and write the following code for the DragDrop and DragEnter events :
private void textBox1_DragEnter(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.FileDrop))
{
e.Effect = DragDropEffects.Copy;
}
}
private void textBox1_DragDrop(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.FileDrop))
{
string[] fileNames = (string[])e.Data.GetData(DataFormats.FileDrop);
textBox1.Lines = fileNames;
}
}
Upvotes: 5