简体   繁体   中英

Object reference not set to an instance of an object. Error

I have a datagridview of my Vendor table and then I also have textboxes of all the fields. I have a setVendor method that sets all the textboxes to the values from the datagrid and then I have a currentcellchanged event that sets the textboxes to the right vendor that is clicked on. Here is my code:

private void dataGridVendors_CurrentCellChanged_1(object sender, EventArgs e)
{
    setVendorInfo((Vendor)allTheVendors[this.dataGridVendors.CurrentRow.Index]);
}

//method to set the textboxes with the vendor information
private void setVendorInfo(Vendor aVendor)
{
    //set all the textboxes
    this.txtVendorId.Text = aVendor.VendorId;
    this.txtName.Text = aVendor.Name;
    this.txtAddressNo.Text = aVendor.AddressNo;
    this.txtStreet.Text = aVendor.Address;
    this.txtCity.Text = aVendor.City;
    this.comboBoxState.Text = aVendor.State;
    this.txtZipcode.Text = aVendor.Zipcode;
    this.txtPhoneNumber.Text = aVendor.PhoneNumber;
}

The error occurs when I delete a record, and happens in the dataGridVendors_CurrentCellChanged event. I'm assuming it happens because once the record that is selected is deleted, then there is no record selected, so it throws the error, but I'm not sure how to fix it.

I did notice that if I use a dataGrid, everything works fine, but when I switch it to a dataGridView this error happens. I would like to use a dataGridView though because I think it looks a little better and I like the autosize columns feature.

Before access to the current row test if it is null

if(this.dataGridVendors.CurrentRow != null )
    setVendorInfo((Vendor)allTheVendors[this.dataGridVendors.CurrentRow.Index]); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM