PJW
PJW

Reputation: 5417

TextBox - Object Reference Not Set To An Instance of an Object

I have a very simple piece of code that is throwing an unexpected error and I am struggling to understand what could possibly be wrong.

private void dataNames_CellDoubleClick(object sender, DataGridViewCellEventArgs e) 
{   
    DataGridViewRow row = dataNames.CurrentCell.OwningRow;
    string val = row.Cells["Name"].Value.ToString();
    txtName.Text = val;
}

The Object dataNames is a DataGridView with only a single Column in it called Names.

When I double click a Name from the Grid I want it to populate the Textbox (txtName)

I fail to see how a Textbox can produce an 'Object not set . . ' error when all I am doing is posting a value to its Text property. When I step through the string 'val' does pick up the correct value from the DataGridView.

Upvotes: 0

Views: 6793

Answers (1)

PJW
PJW

Reputation: 5417

Ironically, having spent a good while unable to find the problem, I go and spot it straight after posting the question.

The error is earlier in the Form_Load event, which calls a custom ClearForm method, which blanks all text fields on the form. However I had done the following :-

txtTitle.Text = null;
txtAge.Text = null;
txtName = null;

Hence I set the textbox itself = null, rather than its text property.

Sometimes the simplest of typos produces the most puzzling of errors!

Upvotes: 1

Related Questions