I have created a class that returns a datatable, when I use the class in a c# winform the dataGridView is populated correctly using the following code
DataTable dt = dbLib.GetData();
if (dt != null)
{
dataGridView1.DataSource = dbLib.GetData();
}
However when I try the same thing with ASP.NET I get a
Object reference not set to an instance of an object.
using the following code
DataTable dt = dbLib.GetData();
if (dt != null)
{
GridView1.DataSource = dt;
GridView1.DataBind();
}
the dbLib class GetData2 is there to prove that it is nothing caused by SQlite or the data
public static DataTable GetData()
{
SQLiteConnection cnn = new SQLiteConnection("Data Source=c:\\test.db");
SQLiteCommand cmd = new SQLiteCommand("SELECT count(Message) AS Occurrences, Message FROM evtlog GROUP BY Message ORDER BY Occurrences DESC LIMIT 25", cnn);
cnn.Open();
SQLiteDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
DataTable dt = new DataTable();
dt.Load(dr);
return dt;
}
public static DataTable GetData2()
{
DataTable dt = new DataTable();
dt.Columns.Add(new DataColumn("Occurrences", typeof(string)));
dt.Columns.Add(new DataColumn("Message", typeof(string)));
DataRow dataRow = dt.NewRow();
dataRow["Occurrences"] = "1";
dataRow["Message"] = "a";
dt.Rows.Add(dataRow);
return dt;
}
the asp code
<asp:GridView ID="GridView1" runat="server">
<Columns>
<asp:BoundField DataField="Occurrences" HeaderText="Occurrences"></asp:BoundField>
<asp:BoundField DataField="Message" HeaderText="Message"></asp:BoundField>
</Columns>
</asp:GridView>
The
NullReferenceExceptionis thrown because you have a null reference toGridView1. This could be cause by a couple of reasons.GridView1at the wrong point in the Asp.net Page Life cycle. Possibly in the constructor of the page? If this is the case moving the logic to PageLoad will fix your problem.GridView1to never be instantiated. If this is the case the best option is to remove the gridview from the markup and re-add it.