c# - 访问其他表中的列时出现空引用异常
问题描述
我正在尝试在 C# 中使用 Linq 对 NWTraders 数据库的产品进行 CRUD 操作。在添加新产品时,我试图显示供应商名称和类别名称,而不是供应商 ID 和类别 ID(它们是产品表的外键)。
我尝试添加新产品,但在我按 OK 将其保存到数据库并更新我的数据网格后不久它就崩溃了。但我注意到新产品正在更新到数据库中,供应商和类别 ID 为 Null,这进一步阻止我访问产品窗口表单本身,因为它无法检索我的相应供应商和类别名称的 ID我在添加期间给新产品。
cmbSupplierName.SelectedIndex 似乎收到一个 NULL 值,并且 this.product.Supplier.Company 正在引发 Null 引用异常。同样是类别的问题。如果我用 if 条件处理它们,那么它仍然会在下面的代码中引发异常。
private void LoadProductInformation()
{
lblProductHeader.Text = "Information about :" + this.product.ProductName;
txtProductID.Text = this.product.ProductID.ToString();
txtProductName.Text = this.product.ProductName;
// Not loading for Add Products as User has to enter the values.
if (this.Mode != ProductViewMode.Add)
{
cmbSupplierName.SelectedIndex = cmbSupplierName.FindString(this.product.Supplier.CompanyName);
cmbCategory.SelectedIndex = cmbCategory.FindString(this.product.Category.CategoryName);
txtQuantityPerUnit.Text = this.product.QuantityPerUnit;
txtUnitPrice.Text = this.product.UnitPrice.Value.ToString("C");
txtUnitsInStock.Text = this.product.UnitsInStock.Value.ToString();
txtUnitsOnOrder.Text = this.product.UnitsOnOrder.Value.ToString();
txtReorderLevel.Text = this.product.ReorderLevel.Value.ToString();
chkDiscontinued.Checked = (this.product.Discontinued == true);
}
}
public void LoadDGVProducts(IEnumerable<Product> products)
{
// If there are no products, do nothing and return from the function.
if (products == null) return;
FetchData(); //fetching all the serach parameters
this.dgvProducts.SelectionChanged -= new System.EventHandler(this.DGVProducts_SelectionChanged);
if (dgvProducts.RowCount == 0)
FormatDGVProducts();
dgvProducts.Rows.Clear();
// Go through every product in the product collection and
// add it as a row in the dgv
foreach (Product prod in products)
{
dgvProducts.Rows.Add(
prod.ProductID, // The ID will not actually be shown since it is given to a column that has the Visible property set to False.
prod.ProductName,
prod.Supplier.CompanyName,
prod.Category.CategoryName,
prod.QuantityPerUnit,
prod.UnitPrice.Value.ToString("C"),
prod.UnitsInStock,
prod.UnitsOnOrder,
prod.ReorderLevel,
prod.Discontinued
);
...........................
}
}
由于供应商和类别 ID 在数据库中接收 Null 值,因此它在“foreach”处向我抛出了异常,因为即使在这种情况下其中一个值为 null 的情况下,它也不会让产品显示在数据网格上。
我不知道我应该在哪里将供应商 ID 连接到 Name 以便它不会在数据库上接收 Null 值。