0

When im trying to set checkbox.checked, i got null refedence exception. I dont know why, it looks like that checkbox isnt initialized.

There is my code

public UpdateProduct(DataGridViewRow row,Form1 form)
{
    this.row = row;
    this.form = form;
    product = row.DataBoundItem as object;
    visibilityCheckBox.Checked = true;
    InitializeComponent();
}

Exception is firing in line visibilityCheckBox.Checked = true;

Please can anybody help me with this issue ? Thanks much !

Patrick Hofman
  • 143,714
  • 19
  • 222
  • 294
Bob T.
  • 261
  • 1
  • 13
  • if you are passing a form and doing this it won't be possible.. you will need invokes – Kavindu Dodanduwa Dec 12 '14 at 09:45
  • This sounds weird. Do you create it dynamically? – TaW Dec 12 '14 at 09:46
  • 1
    @stakx: I closed first too as duplicate of that one, but I guess OP knows what a NRE is. I guess there is just a misunderstanding of how the generated WF code initializes the controls. – Patrick Hofman Dec 12 '14 at 09:47
  • Voted to close since `NullReferenceException`s are really always the same thing, and the linked answer shows how to fix them. It may *look like* `visibilityCheckBox` has been initialized, but if you get that exception, then it *wasn't* initialized (or it was reset to `null`). Add a breakpoint on all lines where that field is initialized/set and see if your code ever stops there. Then figure out why it doesn't stop there. – stakx - no longer contributing Dec 12 '14 at 09:48
  • i forgot that InitializeComponent() must be called first ! Stupid mistake ! :) – Bob T. Dec 12 '14 at 09:48

1 Answers1

3

I guess you didn't call InitializeComponent before, and since you are trying to set it before the call to InitializeComponent, visibilityCheckBox will be null.

Call InitializeComponent first or write another method that does only update the created UI elements.

Patrick Hofman
  • 143,714
  • 19
  • 222
  • 294