Monty Swanson
Monty Swanson

Reputation: 795

Object reference not set to an instance of an object in linq to sql

When running the following code I get the exception "System.Nullreferenceexception:object reference not set to an instance of an object". I believe it has something to with not initializing the allStudents variable but I'm not sure what type allStudents is.

Any help is appreciated

    private void showStudents(string c)
    {
        try
        {
            using (SMDataClassesDataContext db = new SMDataClassesDataContext())
            {

                var allStudents = from t in db.tbl_students
                                  where t.current_class == c
                                  select t;
              dgViewStudents.ItemsSource = allStudents;
            }
        }
        catch (Exception e)
        {
            MessageBox.Show(e.ToString());
        }
    }

Upvotes: 1

Views: 3938

Answers (2)

Monty Swanson
Monty Swanson

Reputation: 795

I managed to solve the problem. Adding a check for null values solved the problem like this:

   if (dgViewStudents != null)
                    dgViewStudents.ItemsSource = allStudents.ToList();

Upvotes: 1

phil
phil

Reputation: 959

You need to force the evaluation of your query and set it up as a DataSource for your DataGridView....assuming the dgViewStudents variable itself is not null and that the allStudents query brings back results, this should work I think.

var bindingSource = new BindingSource();
var allStudents = from t in db.tbl_students
                  where t.current_class == c
                  select t;
bindingSource.DataSource = allStudents.ToList();
dgViewStudents.DataSource = bindingSource;

Upvotes: 0

Related Questions