Reputation: 683
I'm trying to convert my datagridview dgvInput
from Form1
to a DataTable
in an another class Queries
in preparation for SqlBulkCopy
. I pass dgvInput
to a method SaveAll
in my class Queries
with a parameter DataGridView dgv
.
Form1:
public void convert2DT(DataGridView dgv)
{
Queries qry = new Queries();
qry.SaveAll(dgvInput);
}
Class:
class Queries {
public void SaveAll(DataGridView dgv)
{
foreach (DataGridViewRow dr in dgv.Rows)
{
//Create table and insert into cell value.
DataRow dataRow = dt.NewRow();
for (int i = 0; i < noOfColumns; i++)
{
if (i == 0)
>> { dataRow[i] = DateTime.Parse(dr.Cells[i].Value.ToString()); }
else if (i == 7)
{ dataRow[i] = int.Parse(dr.Cells[i].Value.ToString()); }
else
{ dataRow[i] = dr.Cells[i].Value.ToString(); }
}
dt.Rows.Add(dataRow);
}
//SqlBulkCopy Codes
}
}
I'm getting NullReferenceException on line >>
.
Error Message: Object reference not set to an instance of an object.
I have tried setting New
to the dgv
. However, I still get an Exception. From what I've researched the Nested for loops SHOULD do the job right.
How can I resolve this?
Upvotes: 1
Views: 376
Reputation: 30813
The problem is because your dr.Cells[i].Value
is null
and that is caused by the empty last row due to the option AllowUserToAddRows = true
as you figure out later. To solve it, you might put AllowUserToAddRows = false
as what you have done.
But better still to check if dr.Cells[i].Value
is not null
before processing it to make it more robust towards null
cell value wherever it may be found:
for (int i = 0; i < noOfColumns; i++)
{
if (dr.Cells[i].Value == null)
continue; //don't process
if (i == 0)
{ dataRow[i] = DateTime.Parse(dr.Cells[i].Value.ToString()); }
else if (i == 7)
{ dataRow[i] = int.Parse(dr.Cells[i].Value.ToString()); }
else
{ dataRow[i] = dr.Cells[i].Value.ToString(); }
}
And use continue
to ignore the null
cell. Use AllowUserToAddRows = false
only if you really mean it; that is, to prevent user to add rows, not to protect against cell's null
value.
Upvotes: 1