嗨,当我试图在网格视图中运行下面的代码时,我得到了这个错误Attempted to divide by zero。
当错误发生而不被除以零时,如何通过返回零作为除法来避免此错误。
码
protected void gridpandl_RowDataBound(object sender, GridViewRowEventArgs e)
{
try
{
for (int index = 0; index < this.gridpandl.Rows.Count; index++)
{
string Purchase = GetPurchase(this.gridpandl.Rows[index].Cells[0].Text);
string Sales = GetSales(this.gridpandl.Rows[index].Cells[0].Text);
string Serivce = GetService(this.gridpandl.Rows[index].Cells[0].Text);
decimal Profit = (Convert.ToDecimal(Sales) + Convert.ToDecimal(Serivce) - Convert.ToDecimal(Purchase));
decimal Profitprcn = (Profit * 100) / Convert.ToDecimal(Purchase);
this.gridpandl.Rows[index].Cells[2].Text = Purchase;
this.gridpandl.Rows[index].Cells[3].Text = Sales;
this.gridpandl.Rows[index].Cells[4].Text = Serivce;
this.gridpandl.Rows[index].Cells[5].Text = Profit.ToString();
this.gridpandl.Rows[index].Cells[6].Text = Math.Round(Profitprcn, 2).ToString();
}
}
catch (DivideByZeroException ex)
{
}
}发布于 2016-05-10 00:04:15
您应该使用条件运算符(?:)
将Profitprcn行更改为:
decimal Profitprcn = Convert.ToDecimal(Purchase) ==0? 0 : (Profit * 100) / Convert.ToDecimal(Purchase);发布于 2016-05-10 00:10:08
就像这样:
decimal purchasesVal = 0;
decimal Profit = 0;
decimal Profitprcn = 0;
string Purchase = GetPurchase(this.gridpandl.Rows[index].Cells[0].Text);
string Sales = GetSales(this.gridpandl.Rows[index].Cells[0].Text);
string Serivce = GetService(this.gridpandl.Rows[index].Cells[0].Text);
if (!string.IsNullOrEmpty(Purchases) && Convert.ToDecimal(Purchase) > 0)
{
purchasesVal = Convert.ToDecimal(Purchase);
Profit = (Convert.ToDecimal(Sales) + Convert.ToDecimal(Serivce) - purchasesVal);
Profitprcn = (Profit * 100) / purchasesVal;
} https://stackoverflow.com/questions/37127261
复制相似问题