I've been struggling with a NullReferenceException and hope someone here will be able to point me in the right direction. I'm trying to create and populate a DataTable and then show the results in a DataGridView control. The basic code follows, and Execution stops with a NullReferenceException at the point where I invoke the new UpdateResults_Delegate. Oddly enough, I can trace entries.Rows.Count successfully before I return it from QueryEventEntries, so I can at least show 1) entries is not a null reference, and 2) the DataTable contains rows of data. I know I have to be doing something wrong, but I just don't know what.
private delegate void UpdateResults_Delegate(DataTable entries);
private void UpdateResults(DataTable entries)
{
dataGridView.DataSource = entries;
}
private void button_Click(object sender, EventArgs e)
{
Thread t = new Thread(new ThreadStart(PerformQuery));
t.Start();
}
private void PerformQuery()
{
DateTime start = new DateTime(dateTimePicker1.Value.Year,
dateTimePicker1.Value.Month,
dateTimePicker1.Value.Day,
0, 0, 0);
DateTime stop = new DateTime(dateTimePicker2.Value.Year,
dateTimePicker2.Value.Month,
dateTimePicker2.Value.Day,
0, 0, 0);
DataTable entries = QueryEventEntries(start, stop);
Invoke(new UpdateResults_Delegate(UpdateResults), entries);
}
private DataTable QueryEventEntries(DateTime start, DateTime stop)
{
DataTable entries = new DataTable();
entries.Columns.Add("colEventType", typeof(Int32));
entries.Columns.Add("colTimestamp", typeof(Int32));
entries.Columns.Add("colDetails", typeof(String));
...
conn.Open();
using (SqlDataReader r = cmd.ExecuteReader())
{
while (r.Read())
{
entries.Rows.Add(result.GetInt32(0),
result.GetInt32(1),
result.GetString(2));
}
}
return entries;
}