簡體   English   中英

從DataGrid讀取而不是從csv文件讀取到數組/列表

[英]Reading from DataGrid and not from csv file into an array/list

我有以下代碼片段,它讀取帶有數據的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中的行和列中輸入上述數據並處理行和數字。 我不知道該怎么辦,能幫幫我嗎?

您可以使用double 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();
    }
}

據我了解你的問題,請詳細解釋。 我建議用以下方式,

邏輯:聲明一個字符串數組並讀取每一行並將數據填充到字符串數組中。 然后,將其轉換為數據表並將其綁定到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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM