Question

Ok so I just did a quick test to see if my code was set to read properly from the DataGrid, and it does, but once it finishes reading I get the error "Object reference not set to an Instance of an object" and I'm not sure what it's referring to. Is it because the loop continues after the rows has reached the end of the DataGrid?

public static void UploadFromExtrernalSource(PlantAreaCode_CreateView PACCreate)
{
    // For each row in the DataGrid, and for each column, stores the information in a string.
    for (int rows = 0; rows < PACCreate.dataGridView1.Rows.Count; rows++)
    {
        for (int col = 0; col < PACCreate.dataGridView1.Rows[rows].Cells.Count; col++)
        {
            string value = PACCreate.dataGridView1.Rows[rows].Cells[col].Value.ToString();
            Console.WriteLine(value + ",");
        }
    }
}

EDIT: Also when I print to console, it prints each value on a new line. Why?

Was it helpful?

Solution

Problem1 : You are trying to convert the null value from one of the cells into String.

Solution1 : before converting cell value into String do a null check.

Problem 2: you are using Console.WriteLine() method to display each cell value.so that it prints each cell value in a new Row/Line.

Solution 2: you need to use Console.Write() method instead of Console.WriteLine() to print cell values, and once after printing all cell values from a given row you need to use Console.WriteLine() to print new line.

Suggestion: you don't need to declare the string variable value each time in a for loop, so you can move the string variable declaration out of the loop.

Try This:

public static void UploadFromExtrernalSource(PlantAreaCode_CreateView PACCreate)
{
    // For each row in the DataGrid, and for each column, stores the information in a string.
    String value = String.Empty;
    for (int rows = 0; rows < PACCreate.dataGridView1.Rows.Count; rows++)
    {
        for (int col = 0; col < PACCreate.dataGridView1.Rows[rows].Cells.Count; col++)
        {
            if(PACCreate.dataGridView1.Rows[rows].Cells[col].Value!=null)
            { 
              value=PACCreate.dataGridView1.Rows[rows].Cells[col].Value;
              Console.Write(value + ","); 
            }
            else 
            { value=String.Empty; }
        }
        Console.WriteLine();//it prints a new line 
    }
}

OTHER TIPS

hey i think you are trying to convert null value of a cell into string . try to check for the null before converting it to the string hope this will help !

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top