65.9K
CodeProject 正在变化。 阅读更多。
Home

在 DataGridView 单元格中上传和下载文件

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.30/5 (7投票s)

2011年5月25日

CPOL
viewsIcon

52045

downloadIcon

2749

本文档介绍了如何将任何文件上传到 DataGridView 单元格,以及如何从 DataGridView 单元格下载文件。

DataGridViewCells/Image.jpg

引言

本文档介绍了如何将任何文件上传到 datagridview 单元格,以及如何从 datagridview 单元格下载文件。 在附带的项目文件中,我声明了一个模型变量 Dictionary<int, byte[]> _myAttachments,它将附件存储为 Byte 数组,并且键存储 rowIndex

Dictionary<int, byte[]> _myAttachments = new Dictionary<int, byte[]>();

选择附件单元格并单击“上传文件”按钮。 这将弹出一个 FileDialog,供用户选择要上传的所需文件。

以下例程上传用户选择的文件,并在提供的 dataGridViewCell 中显示文件名。

/// <summary>
/// Upload Attachment at the provided DataGridViewCell
/// </summary>
/// <param name="dgvCell"></param>
private void UploadAttachment(DataGridViewCell dgvCell)
{
    using (OpenFileDialog fileDialog = new OpenFileDialog())
    {
        //Set File dialog properties
        fileDialog.CheckFileExists = true;
        fileDialog.CheckPathExists = true;
        fileDialog.Filter = "All Files|*.*";
        fileDialog.Title = "Select a file";
        fileDialog.Multiselect = false;

        if (fileDialog.ShowDialog() == DialogResult.OK)
        {
            FileInfo fileInfo = new FileInfo(fileDialog.FileName);
            byte[] binaryData = File.ReadAllBytes(fileDialog.FileName);
            dataGridView1.Rows[dgvCell.RowIndex].Cells[1].Value = fileInfo.Name;

            if (_myAttachments.ContainsKey(dgvCell.RowIndex))
                _myAttachments[dgvCell.RowIndex] = binaryData;
            else
                _myAttachments.Add(dgvCell.RowIndex, binaryData);
        }
    }
}

DownloadAttachment 例程可以在单元格双击或“下载”按钮单击事件中调用。

/// <summary>
/// Download Attachment from the provided DataGridViewCell
/// </summary>
/// <param name="dgvCell"></param>
private void DownloadAttachment(DataGridViewCell dgvCell)
{
    string fileName = Convert.ToString(dgvCell.Value);

    //Return if the cell is empty
    if (fileName == string.Empty)
        return;

    FileInfo fileInfo = new FileInfo(fileName);
    string fileExtension = fileInfo.Extension;

    byte[] byteData = null;

    //show save as dialog
    using (SaveFileDialog saveFileDialog1 = new SaveFileDialog())
    {
        //Set Save dialog properties
        saveFileDialog1.Filter = "Files (*" + fileExtension + ")|*" + fileExtension;
        saveFileDialog1.Title = "Save File as";
        saveFileDialog1.CheckPathExists = true;
        saveFileDialog1.FileName = fileName;

        if (saveFileDialog1.ShowDialog() == DialogResult.OK)
        {
            byteData = _myAttachments[dgvCell.RowIndex];
            File.WriteAllBytes(saveFileDialog1.FileName, byteData);
        }
    }
}
© . All rights reserved.