1

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());
        }
    }
8
  • 1
    allStudents won't be the problem. Have you used the debugger? What variable is null? Commented Sep 7, 2013 at 18:06
  • 2
    As a side-note, if you're ever unsure about the type of a var, hover the mouse over it, and Intellisense will tell you what type it is, if it can. Commented Sep 7, 2013 at 18:08
  • Are you sure the linq query returns something? Commented Sep 7, 2013 at 18:11
  • the message disappeared when I write dgViewStudents = new DataGrid(); However, the data is no longer loaded to dgViewStudents like this. Commented Sep 7, 2013 at 18:11
  • 1
    If you're using winforms, be sure to let the InitializeComponent -method get called before trying to access the components from your own code. Commented Sep 7, 2013 at 18:14

2 Answers 2

1

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

   if (dgViewStudents != null)
                    dgViewStudents.ItemsSource = allStudents.ToList();
Sign up to request clarification or add additional context in comments.

Comments

0

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;

2 Comments

Doesn't it also need to be DataSource that is set? See edited answer.
unfortunately, the result is still the same.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.