Home > database >  System.NullReferenceException: 'Object reference not set to an instance of an object.' whe
System.NullReferenceException: 'Object reference not set to an instance of an object.' whe

Time:10-19

string[,] Datavalue = new string[GridDelivery.Rows.Count - 1, GridDelivery.Columns.Count];

foreach (DataGridViewRow row in GridDelivery.Rows)
{
    foreach (DataGridViewColumn Col in GridDelivery.Columns)
    {
       // error occurs on this line of code
       Datavalue[row.Index, Col.Index] = GridDelivery.Rows[row.Index].Cells[Col.Index].Value.ToString();
    }
}

I am really struggling with this for the past few days and really can't seem to figure out why it is giving me null. I use the datagridview as my input to get value might that be the reason, if it is please help me find something similar so It can have an easy input.

Included -1 to the GridDelivery.Rows otherwise it read the last row and gave null, but otherwise have no clue how to resolve this issue. GUI is linked ==>

enter image description here

and error displayed after being in debug

enter image description here

CodePudding user response:

try changing your code to :

string[,] Datavalue = new string[GridDelivery.Rows.Count, GridDelivery.Columns.Count];

foreach (DataGridViewRow row in GridDelivery.Rows)
{
    foreach (DataGridViewColumn Col in GridDelivery.Columns)
    {
       Datavalue[row.Index, Col.Index] = GridDelivery.Rows[row.Index].Cells[Col.Index]?.Value?.ToString();
    }
}

I recommend reading these articles:

Jagged Arrays

null conditional operators

  • Related