【发布时间】:2015-04-07 16:29:37
【问题描述】:
我试图在更新网格视图时捕获异常。 代码是
public static int UpdateProduct(
int productID,
string productName,
int supplierID,
int categoryID,
string quantityPerUnit,
decimal unitPrice,
int unitsInStock,
int unitsOnOrder,
int reorderLevel,
bool discontinued)
{
int rowsAffected = 0;
using (SqlConnection connection = ConnectionManager.GetNorthwindConnection())
{
SqlCommand command = new SqlCommand("ttUpdateProduct", connection);
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add("@ProductID", SqlDbType.Int).Value = productID;
command.Parameters.Add("@ProductName", SqlDbType.NVarChar, 40).Value = productName;
command.Parameters.Add("@SupplierID", SqlDbType.Int).Value = supplierID;
command.Parameters.Add("@CategoryID", SqlDbType.Int).Value = categoryID;
command.Parameters.Add("@QuantityPerUnit", SqlDbType.NVarChar, 20).Value = quantityPerUnit;
command.Parameters.Add("@UnitPrice", SqlDbType.Money).Value = unitPrice;
command.Parameters.Add("@UnitsInStock", SqlDbType.SmallInt).Value = unitsInStock;
command.Parameters.Add("@UnitsOnOrder", SqlDbType.SmallInt).Value = unitsOnOrder;
command.Parameters.Add("@ReorderLevel", SqlDbType.SmallInt).Value = reorderLevel;
command.Parameters.Add("@Discontinued", SqlDbType.Bit).Value = discontinued;
rowsAffected = command.ExecuteNonQuery();
}
return rowsAffected;
using (SqlConnection connection = ConnectionManager.GetNorthwindConnection())
{
SqlCommand command = new SqlCommand("ttUpdateProduct", connection);
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add("@ProductID", SqlDbType.Int).Value = productID;
command.Parameters.Add("@ProductName", SqlDbType.NVarChar, 40).Value = productName;
command.Parameters.Add("@SupplierID", SqlDbType.Int).Value = supplierID;
command.Parameters.Add("@CategoryID", SqlDbType.Int).Value = categoryID;
command.Parameters.Add("@QuantityPerUnit", SqlDbType.NVarChar, 20).Value = quantityPerUnit;
command.Parameters.Add("@UnitPrice", SqlDbType.Money).Value = unitPrice;
command.Parameters.Add("@UnitsInStock", SqlDbType.SmallInt).Value = unitsInStock;
command.Parameters.Add("@UnitsOnOrder", SqlDbType.SmallInt).Value = unitsOnOrder;
command.Parameters.Add("@ReorderLevel", SqlDbType.SmallInt).Value = reorderLevel;
command.Parameters.Add("@Discontinued", SqlDbType.Bit).Value = discontinued;
rowsAffected = command.ExecuteNonQuery();
}
return rowsAffected;
异常处理的代码是
protected void ProductGridView_RowUpdated(object sender, GridViewUpdatedEventArgs e)
{
if (e.Exception != null)
{
Master.ErrorMessage = "Cannot Update Record";
e.ExceptionHandled = true;
}
else
{
Master.ResultMessage = "Record Updated Succesfully";
}
但我仍然收到错误:UPDATE 语句与 FOREIGN KEY 约束“FK_Products_Suppliers”冲突。冲突发生在数据库“NORTHWIND”、表“dbo.Suppliers”、列“SupplierID”中。 该语句已终止。 它曾经工作过,但不是每次都工作。 而且我还收到 Asp.net Validation of viewstate MAC failed 错误。
【问题讨论】:
标签: c# asp.net database gridview