Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

drag and drop file into textbox

Tags:

c#

I want to drag and drop a file so that the textbox shows the full file path. I have used the drag enter and drag drop events but I find that they are not entering the events.

private void sslCertField_DragDrop(object sender, DragEventArgs e)
{
    if (e.Data.GetDataPresent(DataFormats.FileDrop, false) == true)
    {
        e.Effect = DragDropEffects.All;
    } 
}

private void sslCertField_DragEnter(object sender, DragEventArgs e)
{
    string file = (string)e.Data.GetData(DataFormats.FileDrop);
    serverURLField.Text = file;
}

Can anyone point out what I am doing wrong?

UPDATE: Does not work if program is set to run with elevated permissions (vista/win 7)

like image 472
michelle Avatar asked Feb 27 '12 11:02

michelle


3 Answers

Check the AllowDrop property of your textbox - it should be set to true. Also, convert drag-drop data to string[] in case of DataFormats.FileDrop, not just string:

string[] files = (string[])e.Data.GetData(DataFormats.FileDrop);
if(files != null && files.Length != 0)
{
    serverURLField.Text = files[0];
}

And I think you should swap code in your drag event handlers - usually you show user that drag-drop is possible in DragEnter and perform actual operation on DragDrop.

like image 96
max Avatar answered Nov 08 '22 02:11

max


Elevated privileges should not have anything to do with it. You also need to implement the DragOver event in addition to the DragDrop that Max answered. This is the code that should be added for DragDrop:

private void textBoxFile_DragOver(object sender, DragEventArgs e) { if (e.Data.GetDataPresent(DataFormats.FileDrop)) e.Effect = DragDropEffects.Copy; else e.Effect = DragDropEffects.None; }

like image 15
Joao Coelho Avatar answered Nov 08 '22 02:11

Joao Coelho


dont run it from visual studio... run the .exe which is created once you build your solution.. hope that helps :)

like image 7
jayesh Avatar answered Nov 08 '22 00:11

jayesh