C# 转换错误 (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["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”类型的异常,但未在用户代码中处理 附加信息:指定的 Actor 阵容无效。

所以问题是在列和特定行中转换值。 为什么我不能那样转换? 我有一列是“数量”,所以我也尝试了 int realQuantity = (int)row["quantity"];

最佳答案

在项目中添加对 System.Data.DataSetExtensions 的引用,并尝试使用此代码来获取命名字段的值。

using System.Data;

...

row.Field<int>("MyColumnName");

检查列的正确类型 (INT => int) 以及是否存在可为空的数据。

关于C# 转换错误 (DataRow),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30685179/

相关文章:

C# - is 运算符 - 检查所有可用转换的可铸性

php - 存储大量内容的建议方法是什么?

mysql - 为什么 information_schema.tables 对行数给出如此不稳定的答案?

c# - 通用接口(interface)的运行时转换

casting - `as` 允许进行哪些转换?

MySQL 使用间接 where 语句更新多个表

c# - C#中的静态成员继承

c# - 使用 Roslyn for C#,如何获取构成返回类型的所有属性的列表?

c# - 覆盖泛型类型方法时出现编译错误

c# - 将方法调用变成可观察事件,好主意吗?