简体   繁体   中英

drag and drop file into textbox

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)

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 .

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; }

不要从visual studio运行它...运行构建解决方案后创建的.exe ..希望有帮助:)

If you're using WPF and it still doesn't work with the answers here (which was my case), you need to use

e.Handled = true;

in the PreviewDragEnter event, as described here and here (they're the same article, but just in case one goes down).

Here is the code snippet, from that source :

private void TextBox_PreviewDragEnter(object sender, DragEventArgs e)
{
    e.Effects = DragDropEffects.Copy;
    e.Handled = true;
}

private void TextBox_PreviewDrop(object sender, DragEventArgs e)
{
    object text = e.Data.GetData(DataFormats.FileDrop);
    TextBox tb = sender as TextBox;
    if (tb != null)
    {
        tb.Text = string.Format("{0}", ((string[])text)[0]);
    }
}

If your visual studio is running under Administrator rights Drag and drop functionality seems not to work.

=> Run visual studio without Admin rights and it will work

Edit: A workaround to test your drag and drop functionality is

  • Open notepad as administrator
  • File -> open
  • from the open dialog you will be able to drag and drop files in your application

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM