具有以下代码,旨在根据Int present更改字段的文本值(即,如果Int为1,则显示“Big Cheese”。
产生以下错误:
错误4最佳重载方法匹配 'MultiviewTester.order_details.FieldDisplay(int)'有一些无效 参数参数1:无法从'object'转换为'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
。由于DB中的“pizza_id”字段设置为INT,我不确定它是从哪里得到的......我是否需要在某处进行某种解析?
答案 0 :(得分:1)
您需要稍微更改一下方法,如下所示:
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
阶梯。