【问题标题】:Reading from DataGrid and not from csv file into an array/list从 DataGrid 而不是从 csv 文件读取到数组/列表中
【发布时间】:2013-01-22 13:03:27
【问题描述】:

我有以下代码 sn-p 读取带有数据的 csv 文件并将它们存储在数组中。

private static void ProcessFile()
{
    var lines = File.ReadLines("Data.csv");
    var numbers = ProcessRawNumbers(lines);
    ****Some variables I use later on****
    var rowTotal = new List<double>();
    var squareRowTotal = new List<double>();
}

我想通过使用 C# 在 DataGridView 中插入数据而不是读取 csv 文件来做同样的事情。

我的 csv 文件格式为:

2,5,6,8,4
5,8,3,5,7
7,7,9,3,5
7,8,4,5,6

我想在DataGridView的行和列中输入上面的数据,并处理行和数字。 我不知道该怎么做,你能帮我吗?

【问题讨论】:

  • 这个 ArrayList 在哪里?
  • 发布更多代码总是比发布更少...
  • @JohnSaunders:File.Readlines 读取 csv 文件中的每一行,而 ProcessRawNumbers 读取每一行中的单个数字。它以列表形式存储,我稍后会使用它来处理。
  • 你的问题是关于 ArrayList,但我在你的代码中没有看到。
  • @JohnSaunders,我认为作者的意思是一个数组或一个列表,他不确定使用哪个。

标签: c# .net csv datagridview


【解决方案1】:

您可以使用双 for 循环进行处理:

for (int rows = 0; rows < dataGrid.Rows.Count; rows++)
{
    for (int cols= 0; cols < dataGrid.Rows[rows].Cells.Count; cols++)
    {
        var value = dataGrid.Rows[rows].Cells[cols].Value.ToString();
    }
}

【讨论】:

    【解决方案2】:

    据我了解您的问题,请始终详细解释。 我建议通过以下方式,

    逻辑: 声明一个字符串数组并读取每一行并将数据填充到字符串数组中。 然后,将其转换为数据表并将其绑定到 DataGridView。 您可以在 Grid 事件中执行 rowTotal 和 SquareTotal。

    private static void ProcessFile()
    {
        string lines;
        string[] ContentData;
        bool blnReadFile = true;
        while (blnReadFile)
        {
            lines = File.ReadLines("Data.csv");
            if (String.IsNullOrEmpty(content))
            {
                blnReadFile = false;
            }
            else
            {
                ContentData = ProcessRawNumbers(lines); /* Ihave retained your metod to get each line */
    
            }
        }
        DataTable dt = ArrayToDataTable(ContentData);
        dg.DataSource = dt; /* dg refers to Datagrid */
        dg.DataBind();
    }
    
    public DataTable ArrayToDataTable(string[] arr)
    {
        DataTable dt = new DataTable();
        string[] header = arr[0].Split(',');
        foreach (string head in header)
        {
            dt.Columns.Add(head);
        }
    
        for (int theRow = 0; theRow < arr.Length; theRow++)
        {
            if (theRow != 0)
            {
                string str = arr[theRow];
                string[] item = str.Split(',');
                DataRow dr = dt.NewRow();
                for (int theColumn = 0; theColumn < item.Length; theColumn++)
                {
                    dr[theColumn] = item[theColumn];
                }
                dt.Rows.Add(dr);
            }
        }
    
        return dt;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-10-03
      • 1970-01-01
      • 1970-01-01
      • 2014-06-12
      • 1970-01-01
      • 1970-01-01
      • 2023-03-27
      • 1970-01-01
      相关资源
      最近更新 更多