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

时间:2018-05-03 14:42:50

标签: c# winforms

我目前正在开发一个Windows表单应用程序,用于比较c#中的2个pdf文件,为此,用户将2个文件放入2个单独的列表框中,一个是“原始”,一个是“新”,验证目的我想知道我是否能够将每个列表框中丢弃的文件数量限制为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]);
            }
        }

1 个答案:

答案 0 :(得分:2)

获取数据并在计数与预期不符时拒绝:

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