1

На форме есть dataGridView. Так же есть файл где-нибудь в проводнике. Хочу сделать так. Если взять этот файл и перенести его на dataGridView, то например в этом dataGridView будет появляться путь к этому файлу (Например C:\1.txt) в качестве новой ячейки. Спасибо!

1
  • Как говорится хотите - делайте. Тут принято помогать, а не делать все за вас. Так что пожалуйста, укажите что именно у вас используется (wpf/winform), а также ваши попытки и описание конкретной проблемы!
    – EvgeniyZ
    22 сен 2018 в 14:48

1 ответ 1

0

Установите свойство AllowDrop и обработайте события DragEnter и DragDrop:

public Form1()
{
    InitializeComponent();
    dataGridView1.AllowDrop = true;
    dataGridView1.DragDrop += new System.Windows.Forms.DragEventHandler(this.DataGridView_DragDrop);
    dataGridView1.DragEnter += new System.Windows.Forms.DragEventHandler(this.DataGridView_DragEnter);
}

private void DataGridView_DragEnter(object sender, DragEventArgs e)
{
    e.Effect = DragDropEffects.Copy;
}

private void DataGridView_DragDrop(object sender, DragEventArgs e)
{
    object val;
    string filepath = "";
    bool found = false;

    //получаем список форматов DragAndDrop
    IDataObject data = e.Data;
    string[] formats = data.GetFormats();            

    //найдем в форматах данные Проводника
    foreach (var fmt in formats)
    {
        //Проводник передает перетаскиваемый файл в виде форматов FileDrop и/или FileNameW,
        //данными для которых является строка или массив строк

        if (fmt == "FileDrop" || fmt == "FileNameW")
        {
            val = data.GetData(fmt);
            if (val == null) continue;

            if (val is string)
            {
                filepath = val as string;
                found = true;
                break;
            }
            else if (val is string[])
            {
                string[] array = val as string[];
                if (array.Length > 0)
                {
                    filepath = array[0];
                    found = true;
                    break;
                }
            }
        }
    }

    if (!found) return; //ничего не найдено

    //добавляем в DataGridView
    DataGridViewCell cell = new DataGridViewTextBoxCell();
    cell.Value = filepath;
    DataGridViewRow row = new DataGridViewRow();
    row.Cells.Add(cell);
    dataGridView1.Rows.Add(row);
}

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.