Click here to Skip to main content
15,891,431 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Instead of loading a file with a:
C#
OpenFileDialog ofd = new OpenFileDialog ();

How do I drag the file into a text box and text box then displays the file path?

Thank you,
KZ
Posted

1 solution

You need to create a new class, based on a TextBox, and handle the Drag-and-drop:

C#
public class MyTextBox : TextBox
    {
    public MyTextBox()
        {
        AllowDrop = true;
        Multiline = true;
        DragDrop += new DragEventHandler(MyTextBox_DragDrop);
        DragEnter += new DragEventHandler(MyTextBox_DragEnter);
        }

    void MyTextBox_DragEnter(object sender, DragEventArgs e)
        {
        e.Effect = DragDropEffects.Copy;
        }

    void MyTextBox_DragDrop(object sender, DragEventArgs e)
        {
        DataObject data = (DataObject)e.Data;
        if (data.ContainsFileDropList())
            {
            string[] rawFiles = (string[])e.Data.GetData(DataFormats.FileDrop);
            if (rawFiles != null)
                {
                List<string> lines = new List<string>();
                foreach (string path in rawFiles)
                    {
                    lines.AddRange(File.ReadAllLines(path));
                    }
                Lines = lines.ToArray();
                }
            }
        }
     }


[edit]
Oops! Went a little far there...That displays the file content, rather than path. Path is even easier: just replace
lines.AddRange(File.ReadAllLines(path));

With
lines.Add(path);

- OriginalGriff
[/edit]
 
Share this answer
 
v2
Comments
Killzone DeathMan 24-May-12 11:20am    
I already done it, it works :D
I forget about the event... :$
Member 13872900 20-Jun-18 3:14am    
How to use this class in my window form?
OriginalGriff 20-Jun-18 3:23am    
How do you think?

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900