Reputation: 1540
I'm currently trying to retrieve records from a database in a WPF application written in C#. I'm using the SQL data reader and it appears to connect fine but the following is giving me a NullReferenceException:
if (isString == true)
{
SqlDataAdapter adapter = new SqlDataAdapter("SELECT PartNumber FROM LoanerItems", loanersConnection);
DataTable datatable = new DataTable();
adapter.Fill(datatable);
for (int i = 0; i < datatable.Rows.Count - 1; i ++)
{
passBackRecords[i] = datatable.Rows[i].ToString();
}
}
Again it would appear that I'm connecting to the database but if I run through the debugger the datatable doesn't appear to be filled.
My connection string in case it might help:
SqlConnectionStringBuilder scsb = new SqlConnectionStringBuilder();
scsb.DataSource = "LLOYD2\\";
scsb.InitialCatalog = "LoanersTest";
scsb.IntegratedSecurity = true;
scsb.ConnectTimeout = 30;
I'm currently using a test database with two records in it instead of the finalized database. I've tried using the Transact-SQL Editor and the records appear just fine.
*EDIT:
After intializing passBackRecords the following started throwing an ArguementOutOfRange exception:
SqlDataAdapter adapter = new SqlDataAdapter("SELECT * FROM LoanerItems", loanersConnection);
DataTable datatable = new DataTable();
adapter.Fill(datatable);
for (int i = 0; i < datatable.Rows.Count - 1; i++)
{
passBackRecords[i] = datatable.Rows[i]["BCPartNumber"].toString;
}
I've tried both:
for (int i = 0; i < datatable.Rows.Count - 1; i++)
and:
for (int i = 1; i < datatable.Rows.Count; i++)
But neither seems to work.
datatable.Rows.Count;
shows that there are two rows in the datatable.
Upvotes: 2
Views: 35486
Reputation: 67898
Even if zero rows were returned, the DataTable
wouldn't be null
. However, there is one place in this line:
passBackRecords[i] = datatable.Rows[i].ToString();
that will fail -when passBackRecords
is null
. Another possible location is this:
.Rows[i].ToString();
if the value in the row is null
you'd also get a NullReferenceException
when calling ToString()
. But I'd almost put money on the fact that you've not yet initialized passBackRecords
.
Upvotes: 3