繁体   English   中英

从datagridview加载选定的.txt文件并在listview中打开文件C#

[英]load selected .txt file from datagridview and open the file in listview c#

所以基本上我有一个数据网格视图,该视图进入一个文件中,并将所有.txt文件名加载到数据网格视图中。 我需要做的是,当我在数据网格视图中单击某个文件时,它将在列表视图中打开该文件的内容。

当我遇到困难时,有人可以帮忙吗?

我猜它像:

如果文件夹中的数据网格视图值= .txt文件,则将内容加载到listview中。

听起来很容易,只是不确定如何编码。

谢谢

我到目前为止有这个,但仍然行不通:

private void gridProfiles_CellClick(object sender, DataGridViewCellEventArgs e)
{
    if (gridProfiles.Rows[e.RowIndex].Cells[0].Value != null)
    {
        var path = gridProfiles.Rows[e.RowIndex].Cells[0].Value.ToString();
        path = Path.Combine(rootDirectory + "\\Profiles\\", path);

        if (File.Exists(path))
        {
            String[] lines = File.ReadAllLines(path);
            foreach (var line in lines)
            {

                lstProcesses.Items.Add(path);
            }
        }

    }
}

当我运行它时,它会获得ti if(file.exists(path),然后跳过它

路线目录:

private static string rootDirectory = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\My File";


static void CreateDirectory()
    {
        string rootDirectory = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\My File";

        if (!Directory.Exists(rootDirectory)) { Directory.CreateDirectory(rootDirectory); }
        if (!Directory.Exists(rootDirectory + "\\Profiles")) { Directory.CreateDirectory(rootDirectory + "\\Profiles"); }

看起来您创建的路径不正确,或者读取的单元格值不正确。 使用接受路径部分列表的重载Path.Combine 另外,除了添加列表path ,还应该添加line

如果文件不存在,则以下代码将向您显示错误消息,并提供尝试查找文件的路径。 如果在网格单元中没有文件名,它也会显示错误消息。

private void gridProfiles_CellClick(object sender, DataGridViewCellEventArgs e)
{
    object value = gridProfiles.Rows[e.RowIndex].Cells[0].Value;

    if (value == null)
    {
        MessageBox.Show("Cannot get file name from grid");
        return;
    }

    var file = value.ToString();
    var path = Path.Combine(rootDirectory, "Profiles", file); // create path

    if (!File.Exists(path))
    {
        MessageBox.Show(path + " not found");
        return;
    }

    foreach(string line in File.ReadLines(path))
        lstProcesses.Items.Add(line); // add line instead of path
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM