本文介绍了拖放异常。桌面对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Drag&将ListView放在文件(目录或任何类型的文件)上。
当我从桌面NullReferenceException拖放我的计算机或Bin时。

I am using Drag & Drop ListView on files (directories or any kind of files). When i drag&drop My Computer or Bin from Desktop NullReferenceException happens.

我只想跳过此元素(在日志文本框中显示某些文本或显示其他内容) )。
我不知道该如何实现。我不知道Desktop中的MyComputer元素是什么样的对象。

All i want is to skip this element (display some text in log textbox or smthing).I have no idea how to achieve that. I don't know what kind of object is MyComputer element from Desktop.

这是在对这个主题逻辑无用之后的代码:

Here's my code after cutting useless to this subject logic:

private void Directories_ListView_DragDrop(object sender, DragEventArgs e)
    {

        string[] DroppedDirectories = (string[]) e.Data.GetData(DataFormats.FileDrop,false); //array of dd files paths
        try
        {
            foreach (var directory in DroppedDirectories) // here Exception  occurs this loop process all dragged and drop files 
            {
                ListViewItem Dir = new ListViewItem(Path.GetFileNameWithoutExtension(directory));
                //Place for some checking Logic
                if (GetDir.IsDirectory(directory))
                {
                   (.....);// Doing some things
                }
                else
                    LogList.Items.Add(DateTime.Now + ": Entry " + Dir.Text + " is not a directory");

            }
        }
        catch(Exception) // it only stops app from crashing, 
        {
            LogList.Items.Add(DateTime.Now + "One of elements was Mycomputer or Bin, process stopped ");
        }
    }


推荐答案

感谢到LarsTech和Abion47,您的解决方案是在这种情况下包装拖放代码:

Thanks to LarsTech and Abion47 your solution is to wrap your drag drop code in this condition:

if (e.Data.GetData(DataFormats.FileDrop, false) != null)
{
    string[] DroppedDirectories = (string[]) e.Data.GetData(DataFormats.FileDrop,false);

    foreach(string directory in DroppedDirectories)
    {
        try
        {
            ListViewItem Dir = new ListViewItem(Path.GetFileNameWithoutExtension(directory));
            //Rest of code
        }
        catch(Exception ex)
        {
            LogList.Items.Add(DateTime.Now + ": Entry " + directory + " is not a directory");
        }
    }
}

这篇关于拖放异常。桌面对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-02 13:48