简体   繁体   English

“ System.InvalidCastException:指定的转换无效”-DateTime

[英]“System.InvalidCastException: Specified cast is not valid” - DateTime

I am updating certain fields in my website, where I get the following error : 我正在更新网站中的某些字段,并在其中收到以下错误:

System.InvalidCastException: Specified cast is not valid. System.InvalidCastException:指定的强制转换无效。

And the code where the error is this(as shown in the error message) : 以及错误所在的代码(如错误消息中所示):

Line 77: productObj.QuantityInStock = dt.Rows[0]["QuantityInStock"].ToString(); 第77行:productObj.QuantityInStock = dt.Rows [0] [“ QuantityInStock”]。ToString();

Line 78:productObj.MinQuantity = dt.Rows[0]["MinQuantity"].ToString(); 第78行:productObj.MinQuantity = dt.Rows [0] [“ MinQuantity”]。ToString();

Line 79:productObj.DateUpdated =(DateTime)dt.Rows[0]["DateUpdated"]; 第79行:productObj.DateUpdated =(DateTime)dt.Rows [0] [“ DateUpdated”]; //This is where error comes //这是错误的来源

Line 80:productObj.DateCreated = (DateTime)dt.Rows[0]["DateCreated"]; 第80行:productObj.DateCreated =(DateTime)dt.Rows [0] [“ DateCreated”];

Line 81: } 第81行:}

My update query is like this : 我的更新查询是这样的:

public int Update(Product obj)
        {
            string query = "update tblProduct set ProdName=@pname,ProdDescription=@pdesc,ProdSize=@psize,ProdPrice=@pprice,QuantityInStock=@qis,MinQuantity=@mq WHERE ProductID=@pid";

            List<SqlParameter> lstParams = new List<SqlParameter>();
            lstParams.Add(new SqlParameter("@pid", obj.ProductID));
            lstParams.Add(new SqlParameter("@pname", obj.ProdName));
            lstParams.Add(new SqlParameter("@pprice", obj.ProdPrice));
            lstParams.Add(new SqlParameter("@pdesc", obj.ProdDescription));
            lstParams.Add(new SqlParameter("@psize", obj.ProdSize));
            lstParams.Add(new SqlParameter("@qis", obj.QuantityInStock));
            lstParams.Add(new SqlParameter("@mq", obj.MinQuantity));

            return DBUtility.ModifyData(query, lstParams);
        }

The Product class looks like this : Product类如下所示:

public class Product : IModel
    {
        public int ProductID;
        public string ProdName;
        public string ProdDescription;
        public string ProdSize;
        public string ProdPrice;
        public int CompanyID;
        public string ProdPhoto;
        public string QuantityInStock;
        public string MinQuantity;
        public int CategoryID;
        public DateTime DateCreated;
        public DateTime DateUpdated;
    }

Error seems to be in this method : 错误似乎在这种方法:

public Product SelectByID(int ID)
        {
            string query = "select * from tblProduct where ProductID=@pid";
            List<SqlParameter> lstParams = new List<SqlParameter>();
            lstParams.Add(new SqlParameter("@pid", ID));

            DataTable dt = DBUtility.SelectData(query, lstParams);

            Product productObj = new Product();
            if (dt.Rows.Count > 0)
            {
                productObj.ProdName = dt.Rows[0]["ProdName"].ToString();
                productObj.ProdDescription = dt.Rows[0]["ProdDescription"].ToString();
                productObj.CompanyID = Convert.ToInt32(dt.Rows[0]["CompanyID"]);
                productObj.ProductID = Convert.ToInt32(dt.Rows[0]["ProductID"]);
                productObj.CategoryID = Convert.ToInt32(dt.Rows[0]["CategoryID"]);
                productObj.ProdSize = dt.Rows[0]["ProdSize"].ToString();
                productObj.ProdPrice = dt.Rows[0]["ProdPrice"].ToString();
                productObj.QuantityInStock = dt.Rows[0]["QuantityInStock"].ToString();
                productObj.MinQuantity = dt.Rows[0]["MinQuantity"].ToString();
                productObj.DateUpdated = (DateTime)dt.Rows[0]["DateUpdated"]; //This where error comes
                productObj.DateCreated = (DateTime)dt.Rows[0]["DateCreated"];
            }

            return productObj;
        }

In my database too I have mentioned the data-type as DateTime , still why is this error coming ? 在我的数据库中,我也提到了数据类型DateTime ,为什么还会出现此错误?

My method where I update looks like this : 我更新的方法如下所示:

protected void btnUpdate_Click(object sender, EventArgs e)
        {
            Product prodObj = new ProductLogic().SelectByID(Convert.ToInt32(Request.QueryString["ID"]));

            prodObj.ProdName = txtName.Text;
            prodObj.ProdPrice = txtPrice.Text;
            prodObj.ProdDescription = txtDesc.Text;
            prodObj.MinQuantity = txtMinQty.ToString();
            prodObj.QuantityInStock = txtInStock.ToString();
            prodObj.ProductID = Convert.ToInt32(Request.QueryString["ID"]); 

            int updateResult = new ProductLogic().Update(prodObj);

            if (updateResult > 0)
            {
                lblUpdateRes.Text = "Detail(s) updated successfully!";
                lblUpdateRes.ForeColor = System.Drawing.Color.Green;
            }
            else
            {
                lblUpdateRes.Text = "There was some error while updating your detail(s). Please try again later!";
                lblUpdateRes.ForeColor = System.Drawing.Color.Red;
            }

        }

Any ideas/suggestions ? 有什么想法/建议吗?

EDIT : 1 Here is an image of my table : 编辑:1这是我的桌子的图像:

在此处输入图片说明

DateTime cannot be null in .NET. .NET中的DateTime不能为null。 If your database can have null values then you can either change the type of DateUpdated to a nullable date/time ( DateTime? ): 如果您的数据库可以具有空值,则可以将DateUpdated的类型更改为可为空的日期/时间( DateTime? ):

productObj.DateUpdated = (DateTime?)(dt.Rows[0]["DateUpdated"] == DBNull.Value ? null : dt.Rows[0]["DateUpdated"]);

or use a "magic" value to represent null: 或使用“魔术”值表示空值:

productObj.DateUpdated = (DateTime)(dt.Rows[0]["DateUpdated"] == DBNull.Value ? DateTime.MinValue : dt.Rows[0]["DateUpdated"]);
productObj.DateUpdated = Convert.IsDBNull(dt.Rows[0]["DateUpdated"])? 
  DateTime.MinValue : (DateTime)dt.Rows[0]["DateUpdated"];

or, if productObj.DateUpdated is nullable DateTime? 或者,如果productObj.DateUpdated是可为null的DateTime? ,

if (!Convert.IsDBNull(dt.Rows[0]["DateUpdated"]))
  productObj.DateUpdated.Value = (DateTime)dt.Rows[0]["DateUpdated"];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 指定的转换无效-System.InvalidCastException - Specified cast is not valid - System.InvalidCastException System.InvalidCastException:指定的强制转换无效 - System.InvalidCastException: Specified cast is not valid System.InvalidCastException:&#39;指定的强制转换无效。 - System.InvalidCastException: 'Specified cast is not valid.' System.InvalidCastException:指定的强制转换在.ExecuteScalar上无效 - System.InvalidCastException: Specified cast is not valid at .ExecuteScalar System.InvalidCastException:指定的强制转换无效(linq查询) - System.InvalidCastException: Specified cast is not valid (linq query) System.InvalidCastException:指定的强制转换无效。 -DynamoDB查询 - System.InvalidCastException: Specified cast is not valid. - DynamoDB Query System.InvalidCastException:“指定的演员表无效。” C# MYSQL - System.InvalidCastException: 'Specified cast is not valid.' C# MYSQL C#System.InvalidCastException:指定的转换无效 - C# System.InvalidCastException: Specified Cast is not valid System.InvalidCastException:指定的强制转换无效的C# - System.InvalidCastException: Specified cast is not valid C# Xamarin 形式:System.InvalidCastException:“指定的强制转换无效。” - Xamarin forms: System.InvalidCastException: 'Specified cast is not valid.'
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM