c# - 如何只允许将一个文件放入列表框控件c#

标签 c# winforms

我目前正在开发一个 Windows 窗体应用程序,用于比较 C# 中的 2 个 pdf 文件,为此,用户将这 2 个文件放入 2 个单独的列表框中,在我的情况下,一个是“原始”,一个是"new",对于验证目的我想知道是否能够将每个列表框删除的文件数量限制为 1 个。

  public Compare()
        {
            InitializeComponent();

            AllowDrop = true;
            OriginalDrop_LstBox.DragDrop += new DragEventHandler(OriginalDrop_LstBox_DragDrop);
            OriginalDrop_LstBox.DragEnter += new DragEventHandler(OriginalDrop_LstBox_DragEnter);
            NewDrop_LstBox.DragDrop += new DragEventHandler(NewDrop_LstBox_DragDrop);
            NewDrop_LstBox.DragEnter += new DragEventHandler(NewDrop_LstBox_DragEnter);
        }



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

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

            for (int i = 0; i < s.Length; i++)
            {
                OriginalDrop_LstBox.Items.Add(s[i]);
            }
        }

最佳答案

获取数据并在计数与您期望的不匹配时拒绝它:

private void OriginalDrop_LstBox_DragEnter(object sender, DragEventArgs e)

if (e.Data.GetDataPresent(DataFormats.FileDrop))
{
    var files = (string[])e.Data.GetData(DataFormats.FileDrop);
    if (files.Length == 1 && OriginalDrop.Items.Count == 0)
    {
        e.Effect = DragDropEffects.All;
    }
    else
    {
        e.Effect = DragDropEffects.None;
    }
}

关于c# - 如何只允许将一个文件放入列表框控件c#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50157807/

相关文章:

c# - System.UnauthorizedAccessException 被拒绝错误

c# - 使用 c#/htmlagilitpack 无法从 amazon.com 获取正确的信息

c# - 模糊图像的选定部分

C# 窗体 : Add an "Select from list..." placeholder to databound combobox

wpf 与 winforms 通过可定制的 UI 进行比较

c# - 存储库中的错误处理 (API REST)

c# - 为什么不推荐使用堆来排序LinkedList?

c# - 使用属性包装方法 C#

c# - 对 Windows 窗体控件进行线程安全调用

c# - 如何将点击事件处理程序分配给绘制矩形的一部分?