0

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.

1 Answer 1

3

Before access to the current row test if it is null

if(this.dataGridVendors.CurrentRow != null )
    setVendorInfo((Vendor)allTheVendors[this.dataGridVendors.CurrentRow.Index]); 
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.