user2049436
user2049436

Reputation: 61

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

I have the following code snippet that reads a csv file with data and stores them in an array.

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>();
}

I would like to do the same by inserting data in the DataGridView using C# and not reading through a csv file.

My csv file is of the form:

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

I would like to enter the above data in rows and columns in DataGridView and process the lines and numbers. I'm not sure how to do it, can you please help me?

Upvotes: 4

Views: 340

Answers (2)

MahaSwetha
MahaSwetha

Reputation: 1066

As far as I understand your question,Please,explain in detail always. I am suggesting in the following way,

Logic: Declare an string array and read each line and fill the data into string array. Then,convert it to an datatable and bind it to DataGridView. You can do the rowTotal and SquareTotal in Grid events.

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;
}

Upvotes: 0

Next Door Engineer
Next Door Engineer

Reputation: 2896

You can process using a double for loop:

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();
    }
}

Upvotes: 1

Related Questions