不能从对象转换为INT
问题描述:
有以下代码,旨在改变基础上,诠释目前现场的文本值(即如果int是1,则显示“大奶酪”代替。不能从对象转换为INT
提供了以下错误:
转换错误4为 'MultiviewTester.order_details.FieldDisplay(INT)' 最好的重载的方法匹配有一些无效 参数参数1:无法从 '对象' 到 'INT'
.aspx页面中编号:
<ItemTemplate>
<asp:Label runat="server" Text='<%#FieldDisplay(Eval("pizza_id")) %>'>
</asp:Label>
</ItemTemplate>
代码隐藏
protected string FieldDisplay(int pizza_id)
{
string rtn = "DefaultValue";
if (pizza_id == 1)
{
rtn = "Big Cheese";
}
else if (pizza_id == 2)
{
rtn = "BBQ Beef";
}
else if (pizza_id == 3)
{
rtn = "Chicken and Pineapple";
}
else if (pizza_id == 4)
{
rtn = "Pepperoni Feast";
}
else if (pizza_id == 5)
{
rtn = "Vegetarian";
}
return rtn;
}
一直得到错误Object cannot be converted to Int
。我不知道它是从哪里得到的,因为数据库中的“pizza_id”字段设置为INT ....我是否需要在某处进行某种解析?
答
你需要如下改变你的方法一点点:
protected string FieldDisplay(object pizza_id)
{
string rtn = "DefaultValue";
int pizzaID=0;
if(int.TryParse(Convert.ToString(pizza_id), out pizzaID))
{
if (pizzaID== 1)
{
rtn = "Big Cheese";
}
else if (pizzaID== 2)
{
rtn = "BBQ Beef";
}
else if (pizzaID== 3)
{
rtn = "Chicken and Pineapple";
}
else if (pizzaID== 4)
{
rtn = "Pepperoni Feast";
}
else if (pizzaID== 5)
{
rtn = "Vegetarian";
}
}
return rtn;
}
我建议你使用switch
代替if else
阶梯。