[英]C# Cast Error (DataRow)
我正在網站上。 我無法轉換表中row [“”]中的數字值。 我的代碼是:
public partial class bought : System.Web.UI.Page
{
protected int id;
protected DataRow row;
protected void Page_Load(object sender, EventArgs e)
{
if (Session["admin"] == null || (bool)Session["admin"] == false) //si es que no eres admin, vete de la pagina porque hay paginas que solo admin puede ver.
{
Response.Redirect("home.aspx");
}
if (Request.Form["id"] != null)
{
id = int.Parse(Request.Form["id"]);
}
string sql = "";
int quantity = int.Parse(Request.Form["quantity"]);
DataTable dt = DAL.GetTable("select * from item where id =" + id);
row = dt.Rows[0];
int realQuantity = (int)row[5];
int finalQuantity = realQuantity - quantity;
OleDbConnection con = DAL.GetConnection();
con.Open(); //ya esta listo, entonces abrimos el Database
if (con.State == ConnectionState.Open) //si la conexion esta abierta...
{
if (realQuantity == quantity)
{
sql = "DELETE FROM item WHERE (id =" + id + ")";
}
else if (realQuantity > quantity)
{
sql = "UPDATE item SET quantity = " + finalQuantity + " WHERE (id = "+id+")";
}
OleDbCommand cmd = DAL.GetCommand(con, sql);
int num = cmd.ExecuteNonQuery(); //es insert y no select. NonQuery es que no devuelve.
con.Close();
}
else Response.Redirect("buyItems.aspx?err=Error en la base de datos");
Response.Redirect("home.aspx");
}
}
當我運行代碼(並且我也進行調試)時,錯誤在這里:
App_Web_mavjxnn0.dll中發生類型為'System.InvalidCastException'的異常,但未在用戶代碼中處理。其他信息:指定的強制轉換無效。
因此,問題在於在列和特定行中強制轉換值。 我為什么不能那樣投射? 我有一列是“ quantity”,所以我也嘗試了int realQuantity = (int)row["quantity"];
在您的項目中添加對System.Data.DataSetExtensions的引用,然后嘗試使用此代碼來獲取命名字段的值。
using System.Data;
...
row.Field<int>("MyColumnName");
檢查列的正確類型(INT => int)以及是否有可為空的數據。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.