LINQtoSQL error??

P

Paolo

I'm getting an error "Object reference not set to an instance of an object."
with line number shown as <### as i try to popuate a DataGridView:

private void btnList_Click(object sender, EventArgs e)
{
var act_types = <###
from a in db.Activities
from t in db.Types
where a.Activity_Type == t.Type_Id

orderby a.Activity_Date
select new
{
a.Activity_Date,
t.Type_Desc,
a.Activity_Distance,
a.Activity_Duration,
a.Activity_Route
};

dgvList.DataSource = act_types; // DataGridView
}

This model appears identical to many examples I've seen so what am I missing?
 
J

Jon Skeet [C# MVP]

Paolo said:
I'm getting an error "Object reference not set to an instance of an object."
with line number shown as <### as i try to popuate a DataGridView:

private void btnList_Click(object sender, EventArgs e)
{
var act_types = <###
from a in db.Activities
from t in db.Types
where a.Activity_Type == t.Type_Id

orderby a.Activity_Date
select new
{
a.Activity_Date,
t.Type_Desc,
a.Activity_Distance,
a.Activity_Duration,
a.Activity_Route
};

dgvList.DataSource = act_types; // DataGridView
}

This model appears identical to many examples I've seen so what am I missing?

Where are you getting db from, and is it definitely non-null?
 
P

Paolo

Jon: this is my code so far:

public partial class frmMain : Form
{
DBDataContext db = null; // DBDataContext defined in DBDataContext.cs

public frmMain()
{
InitializeComponent();

string cnStr = <connection string> // actual string snipped

DBDataContext db = new DBDataContext(cnStr);
}

private void btnList_Click(object sender, EventArgs e)
{
var act_types =
from a in db.Activities
from t in db.Types
where a.Activity_Type == t.Type_Id

orderby a.Activity_Date
select new
{
a.Activity_Date,
t.Type_Desc,
a.Activity_Distance,
a.Activity_Duration,
a.Activity_Route
};
dgvList.DataSource = act_types;
}
}

The query worked perfectly when it was part of frmMain
 
J

Jon Skeet [C# MVP]

Paolo said:
Jon: this is my code so far:

The query worked perfectly when it was part of frmMain

Yes, it would. Look at this line of your constructor:

DBDataContext db = new DBDataContext(cnStr);

That's declaring a new *local variable* called db - it's not setting
the instance variable. Change it to this:

db = new DBDataContext(cnStr);
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top