C# C转换错误(数据行)
我在一家网站工作。我无法转换表中第[]行中的数值。我的代码是:C# C转换错误(数据行),c#,mysql,casting,datatable,datarow,C#,Mysql,Casting,Datatable,Datarow,我在一家网站工作。我无法转换表中第[]行中的数值。我的代码是: 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["
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=introw[quantity] 在项目中添加对System.Data.DataSetExtensions的引用,并尝试使用此代码获取命名字段的值
using System.Data;
...
row.Field<int>("MyColumnName");
检查列INT=>INT的正确类型,以及是否有可为空的数据。您能看到行[quantity]中的实际值吗?使用星号选择字段的危险从未完全解释过。您确定查询返回的6列确实是Quantity列吗?当然,这是假设您的db中对于该列确实有一个整数数据类型,而不是不能转换为整数的数据类型。当然可以,所以试试Fabio的建议:在调试器中检查行[quantity]的值。另外,请接受Steve的建议:如果您执行SELECT*操作,然后按索引而不是名称提取列值,那么您的代码将非常脆弱-我几乎可以保证这将在将来中断。数据库中quantity列的数据类型是什么?感谢您的帮助!但是我怎样才能让人们知道这个问题已经在评论中解决了?你需要接受一个anwser而不是评论: