0

我有我的供应商表的 datagridview,然后我也有所有字段的文本框。我有一个 setVendor 方法,将所有文本框设置为数据网格中的值,然后我有一个 currentcellchanged 事件,将文本框设置为单击的正确供应商。这是我的代码:

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;
}

当我删除记录时发生错误,并且发生在 dataGridVendors_CurrentCellChanged 事件中。我假设它发生是因为一旦删除了选定的记录,就没有选择记录,所以它会抛出错误,但我不知道如何修复它。

我确实注意到,如果我使用 dataGrid,一切正常,但是当我将其切换到 dataGridView 时,会发生此错误。不过,我想使用 dataGridView,因为我认为它看起来更好一些,而且我喜欢自动调整列大小的功能。

4

1 回答 1

3

在访问当前行之前测试是否为空

if(this.dataGridVendors.CurrentRow != null )
    setVendorInfo((Vendor)allTheVendors[this.dataGridVendors.CurrentRow.Index]); 
于 2012-04-29T19:51:18.177 回答