【问题标题】:C# ListBox Does Not Allow Drag & DropC# ListBox 不允许拖放
【发布时间】:2019-05-28 03:08:33
【问题描述】:

我无法将文件拖放到我的列表框中。我已将 AllowDrop 属性设置为 true 并添加了以下代码,但光标是一个圆圈,中间有一条线,不允许我删除文件:

public List<string> files = new List<string>();
    public Form1()
    {
        InitializeComponent();
        this.listBox1.DragDrop += new DragEventHandler(this.listBox1_DragDrop);
        this.listBox1.DragEnter += new DragEventHandler(this.listBox1_DragEnter);
    }



    private void listBox1_DragEnter(object sender, DragEventArgs e)
    {
        try
        {
            if (e.Data.GetDataPresent(DataFormats.FileDrop))
            {
                e.Effect = DragDropEffects.All;
            }
            else
            {
                e.Effect = DragDropEffects.None;
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }

    private void listBox1_DragDrop(object sender, DragEventArgs e)
    {
        try
        {
            string[] s = (string[])e.Data.GetData(DataFormats.FileDrop, false);
            int i;

            for (i = 0; i < s.Length; i++)
            {
                listBox1.Items.Add(Path.GetFileName(s[i]));
                files.Add(s[i]);
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }

我已经在另一个项目中成功完成了这项工作,唯一的区别是我现在使用的是 Visual Studio 2017。关于为什么这不起作用的任何想法?

【问题讨论】:

  • 我刚刚意识到我需要将 [STAThread] 添加到我的 Program.cs 文件中才能使其正常工作。
  • 参见我在 Code Project 上的文章 Drag-and-Drop ListBox。您也可以在那里下载和实施。

标签: c# drag-and-drop listbox


【解决方案1】:

我刚刚意识到我需要将 [STAThread] 添加到我的 Program.cs 文件中才能使其正常工作

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-21
    • 2012-01-04
    • 1970-01-01
    • 2013-02-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多