[英]Add calculated column to a GridView
I have a GridView with two columns and I want to add a third column which will be column A divided by column B. I added a template field but I am getting a divide by zero error. 我有一个包含两列的GridView,我想添加第三列,即A列除以B列。我添加了一个模板字段,但出现零除错误。 How can I check for zero values to stop the error message?
如何检查零值以停止错误消息?
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="lblCalc" runat="server" >
<%# Convert.ToDecimal(Eval("val1").ToString()) / Convert.ToDecimal(Eval("val2").ToString()) %>
</asp:Label>
</ItemTemplate>
</asp:TemplateField>
Yes, you sure can. 是的,您当然可以。 You can even do that inline, but that would clutter your markup too much, so I would suggest moving this code to code behind.
您甚至可以内联执行此操作,但这会使您的标记过于混乱,因此建议将这段代码移到后面的代码中。
protected decimal Calculate(string a, string b)
{
decimal ad = Convert.ToDecimal(a);
decimal bd = Convert.ToDecimal(bd);
if (bd == 0)
{
return 0; // or whatever
}
return ad / bd;
}
To call this: 调用此:
<asp:Label ID="lblCalc" runat="server" >
<%# Calculate(Eval("val1").ToString(), Eval("val2").ToString()) %>
</Label>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.