Windows Form Application, C#, in VS2010 Express.

I get the "Object reference not set to an instance of an object." error with the line of code below, when I attempt to close the Form.

Int32 myID = Convert.ToInt32(((DataRowView)projectBindingSource.Current).Row.ItemArray[0]);

This is a simple form with two data-bound controls. The record has three fields, and I'm attempting to grab the non-bound field. The code runs fine, except for the error when I close the form.

That line of code is in a comboBox1_SelectedIndexChanged event handler, so not sure why the error fires on form close. Any suggestions?

It sounds like you are triggering events in your form_closed or form_closing event. Without seeing more code, that's the best I can do for you.

Those events are not wired, no. I'm not at the machine with the code, but will post more when I can. Thanks for the reply.

Please always verify the presence of an object.

DataRowView rv=((DataRowView)projectBindingSource.Current).Row;
Int32 myID=0;
if(rv!=null)
   myID = Convert.ToInt32(rv.ItemArray[0]);

I cannot get that block of code to work... but I suspect that with a databound Combobox, the SelectIndexChanged event fires what the data is bound and when it is un-bound, which would happen during form load, and unload. So I should wrap my code in an if block so it doesn't try to execute when the form is closing.

That's my theory.

Here's my code for the combobox event. The idea is that when the user changes the ComboBox to a new value, insert a new record into the database with the Identify field ("id") of the same record that the ComboBox uses for it's value, and to grab the id field of the record the ComboBox changed to.

As I mentioned, this does work except when the program is closed, in which case line 11 throws an error. My guess is because during shutdown the data objects go away. What I don't understand is why this event code fires when the program closes.

private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            timer1.Stop();
            StartStopTimes.StopTime = DateTime.Now;
            timesTableAdapter.Insert(StartStopTimes.ProjectID, StartStopTimes.StartTime, DateTime.Now);

            timer1.Start();
            StartStopTimes.StartTime = DateTime.Now;
            labStart.Text = StartStopTimes.StartTime.ToLongTimeString();

            Int32 myID = Convert.ToInt32(((DataRowView)projectBindingSource.Current).Row.ItemArray[0]);
            StartStopTimes.ProjectID = myID;
                         
        }
This article has been dead for over six months. Start a new discussion instead.