user3171911
user3171911

Reputation: 21

Geting error as Object reference not set to instance of an object when clicking save button

private void btnSave_Click(object sender, EventArgs e)
    {
        int i = 0;

        foreach (DataGridViewRow row in dataGridView1.Rows)
        {
            if (!row.IsNewRow)

                {
                    string keyword = row.Cells[0].Value.ToString();
                    string fname = row.Cells[1].Value.ToString();
                    string comm = row.Cells[2].Value.ToString();
                    string retur = row.Cells[3].Value.ToString();
                    string message = row.Cells[4].Value.ToString();
                    string inm = this.cmbInNa.Text.ToString();
                    i = pbl.fsave(keyword, fname, comm, retur, message, inm);
                    if (i > 0)
                    {
                        MessageBox.Show("Success");
                    }
                    else
                    {
                        MessageBox.Show("Error");
                    }
                }                            
        }
    }

While clicking btnSave, I'm getting "object reference not set to instance of an object". I want to insert values in gridview. What is the issue?

Upvotes: 1

Views: 1869

Answers (2)

Erik Carlsson
Erik Carlsson

Reputation: 1

Had the same problem with null exception, followed the hints given here, but have no null fields in the table.

The problem was, that I had disabled a button-column by removing the following line:

dataGridView1.CellClick += new DataGridViewCellEventHandler(sense_button_Click);

So, to every button column, you HAVE to give an event handler, which can have no code. Otherwise you will get an exception from whatever you click on the table.

Upvotes: 0

Kurubaran
Kurubaran

Reputation: 8902

Any of those grid cell value could be null applying ToString() on null values would result in exception.

string keyword = row.Cells[0].Value.ToString();

Best way is to check for null before doing a ToString(). You could use a Turnary operator.

string keyword = (null != row.Cells[0].Value) ? row.Cells[0].Value.ToString() : string.Empty;

Upvotes: 2

Related Questions