无法将类型字符串隐式转换为int。 [英] cannot implicitly convert type string to int.
本文介绍了无法将类型字符串隐式转换为int。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
public 产品()
{
this .Carts = new HashSet< cart>();
}
public int Id {获得跨度>; set ; }
public int TypeId { get 跨度>; set ; }
public string 名称{ get 跨度>; set ; }
public int 价格{获得跨度>; set ; }
public string 说明{获得跨度>; set ; }
public string 图片{ get 跨度>; set ; }
public virtual ICollection< cart>购物车{获取; set ; }
public virtual ProductType ProductType { get < /跨度>; set ; }
}
private 产品CreateProduct()
{
产品product = < span class =code-keyword> new Product();
product.Name = txtName.Text;
product.Price = txtPrice.Text;
product.TypeId = Convert.ToInt32(ddlType.SelectedValue);
product.Description = txtDescription.Text;
product.Image = ddlImage.SelectedValue;
返回产品;
}
它在 product.Price = txtPrice.Text中出错; 无法将类型字符串隐式转换为int。 price的数据类型是int。请告诉我是否必须转换它或更改db中的数据类型。
解决方案
txtPrice.Text
是a字符串
product.Price
是int
是的,在将文本分配给价格$ c之前,您必须将文本转换为整数$ c>属性
我建议使用int.TryParse()进行转换 - 请参阅如何:将字符串转换为数字(C#编程指南) [ ^ ]
Price的数据类型为int,但是的数据类型txtPrice.Text
是一个字符串。您首先必须将txtPrice.Text
解析为int,然后才能将其存储在product.Price
中:
int 价格;
if ( int .TryParse(txtPrice.Text, out 价格))
{
product.Price = price;
}
其他
{
// < span class =code-comment>输入无法解析为整数;显示相应的错误消息
}
有关int.TryParse
的更多信息: MSDN - Int32.TryParse方法(系统) [ ^ ]
public Product()
{
this.Carts = new HashSet<cart>();
}
public int Id { get; set; }
public int TypeId { get; set; }
public string Name { get; set; }
public int Price { get; set; }
public string Description { get; set; }
public string Image { get; set; }
public virtual ICollection<cart> Carts { get; set; }
public virtual ProductType ProductType { get; set; }
}
private Product CreateProduct()
{
Product product = new Product();
product.Name = txtName.Text;
product.Price = txtPrice.Text;
product.TypeId = Convert.ToInt32(ddlType.SelectedValue);
product.Description = txtDescription.Text;
product.Image = ddlImage.SelectedValue;
return product;
}
it gives an error in product.Price = txtPrice.Text; cannot implicitly convert type string to int. the datatype of price is int. please tell me if i have to convert it or change the datatype in db.
解决方案
txtPrice.Text
is astring
product.Price
is anint
So yes, you have to convert the text to an integer before you assign it to thePrice
property
I suggest using int.TryParse() to do the conversion - see How to: Convert a String to a Number (C# Programming Guide)[^]
The datatype of Price is int, but the one oftxtPrice.Text
is a string. You first have to parsetxtPrice.Text
to an int before you can store it inproduct.Price
:
int price; if (int.TryParse(txtPrice.Text, out price)) { product.Price = price; } else { // input could not be parsed as integer; show appropriate error message }
More information aboutint.TryParse
: MSDN - Int32.TryParse Method (System)[^]
这篇关于无法将类型字符串隐式转换为int。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文