【问题标题】:load .txt file into gridview c#将.txt文件加载到gridview c#
【发布时间】:2013-07-05 15:09:58
【问题描述】:

所以我快到了,只需要从我的记事本中的文本文件中加载信息,保存如下:

项目1

项目2

项目3

项目4

我的第一次尝试是这样的:

gridProfiles.Columns.Add("App Name", "Active");
        int i = 0;
        foreach(char snif in "D:\\ProfileAppName.txt")
        {
            gridProfiles.Rows.Add();
            gridProfiles.Rows[i].Cells[0].Value = snif;
            i++;
        }

但这只是将文件名加载到文本文件中

我的下一个尝试是:

 gridProfiles.Columns.Add("App Name", "Active");
        int i = 0;
        foreach (string snif in "D:\\ProfileAppName.txt")
        {
            string[] values = snif.Split(' ');
            int j = 0;
            foreach (string value in values)
            {
                gridProfiles.Rows.Add();
                gridProfiles.Rows[i].Cells[0].Value = snif;
                j++;
            }
        }
        i++;

但我收到错误“无法将类型 'char' 转换为 'string'

谁能帮帮我?我快到了,但我无法找到它

【问题讨论】:

    标签: c# gridview load text-files


    【解决方案1】:

    您正在循环此字符串中的所有字符:"D:\\ProfileAppName.txt"。我假设您想循环文件中的所有行。然后你可以使用File.ReadLines:

    foreach(string line in File.ReadLines("D:\\ProfileAppName.txt"))
    {
        gridProfiles.Rows.Add();
        gridProfiles.Rows[i].Cells[0].Value = line;
        i++;
    }
    

    【讨论】:

    • 这就像一种享受.. 很快就会标记为正确,现在唯一的事情是,它全部加载到 1 列中,我需要它加载到多个列中。任何想法?谢谢
    【解决方案2】:

    读取文件的内容你可以这样做:

    int i = 0;
    foreach(string row in File.ReadAllLines("D:\\ProfileAppName.txt"))
    {
        if (i % 2 == 0)
            gridProfiles.Rows.Add();
        gridProfiles.Rows[i / 2].Cells[i % 2].Value = line;
        i++;
    }
    

    【讨论】:

    • 你的答案和其他人类似,也可以,加载到一列,无论如何让它加载到多列?
    • 我在您的文件示例中没有看到任何列。列是否以任何方式分开?如果您需要更多帮助,请提供更好的文件示例。
    • 我能够将文本框保存到文本文件中的唯一方法是像在页面下方那样单一,所以除非有办法将它们保存在一行/行中?
    • 你的意思是每一行都是一列?我不明白。
    • 好的,所以基本上我程序的这一部分由一些文本框组成,这些文本框保存到 .txt 文件中。但是当它们保存时。他们保存在一个列表中,而不是彼此相邻的页面。它起作用了,所以它们都加载到了第一列。但我需要每隔一个加载到gridview的第二列,第一个加载到dgv的第一列
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-26
    • 1970-01-01
    • 1970-01-01
    • 2021-09-11
    • 2013-02-19
    • 1970-01-01
    相关资源
    最近更新 更多