【问题标题】:Adding file name and safe file name to DataGridView将文件名和安全文件名添加到 DataGridView
【发布时间】:2014-08-27 10:09:19
【问题描述】:

这看起来应该很简单。当我使用 OpenFileDialog 时,我有一个程序在两个单独的列中提取文件名和文件路径。我正在使用一个 foreach 语句,它为 OpenFileDialog 中选择的每个文件添加一行(注意,我在我的 ofd 中使用了多选)。

当我选择一个文件时,一切正常,因为数组中只有 1 个文件名(字符串)。但是,当我选择 2 个文件时,我的 DataGridView 中添加了四行。我知道我不应该在 dataGridView1.Rows.Add 函数中使用 2 个 foreach 语句。

有没有一种简单的方法可以在不使用dataGridView1.Rows.AddAdd 部分的情况下将数组添加到列中?我想在第三列的每个单元格中添加一个字符串(来自我的 OpenFileDialog 数组),但不是每次都添加一行。

 private void button1_Click(object sender, EventArgs e)
        {
            ofd.Filter = "*.SFP, *.SFL|*.sfp; *.sfl";
            ofd.Multiselect = true;


        if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
        {
            string[] selectedFiles = ofd.SafeFileNames;
            string[] filePaths = ofd.FileNames;

            foreach (string selectedFile in selectedFiles)
            foreach (string filePath in filePaths)
            {
                dataGridView1.Rows.Add(selectedFile, "", filePath);
            }
        }
    }

我也尝试了以下方法,并在下面的屏幕截图中收到了结果:

    private void button1_Click(object sender, EventArgs e)
    {
        ofd.Filter = "*.SFP, *.SFL|*.sfp; *.sfl";
        ofd.Multiselect = true;


        if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
        {
            string[] selectedFiles = ofd.SafeFileNames;
            string[] filePaths = ofd.FileNames;

            foreach (string selectedFile in selectedFiles)
            {
                dataGridView1.Rows.Add(selectedFile);
            }
            foreach (string filePath in filePaths)
            {
                dataGridView1.Rows.Add("", "", filePath);
            }
        }
    }

我真的认为这很简单。新程序员来了。谢谢你的帮助。

【问题讨论】:

    标签: datagridview openfiledialog


    【解决方案1】:
    openFileDialog1.Multiselect = true;
            if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                string[] selectedFiles = openFileDialog1.SafeFileNames;
                string[] filePaths = openFileDialog1.FileNames;
                for (int i = 0; i < openFileDialog1.FileNames.Count() - 1; i++)
                {
                    dataGridView1.Rows.Add(selectedFiles[i], filePaths[i]);
                }
            }
    

    【讨论】:

    • 你可能想解释你的代码。这将对 SO 用户有很大帮助。
    猜你喜欢
    • 1970-01-01
    • 2021-09-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-28
    • 1970-01-01
    • 2022-01-08
    • 2018-07-16
    相关资源
    最近更新 更多