如何避免DivideByZeroException

Aym*_*man 1 c# asp.net gridview

嗨,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)
    {

    }
}
Run Code Online (Sandbox Code Playgroud)

Chr*_*ken 8

您应该使用条件运算符(?:).

Profitprcn行更改为:

decimal Profitprcn = Convert.ToDecimal(Purchase) ==0? 0 : (Profit * 100) / Convert.ToDecimal(Purchase);
Run Code Online (Sandbox Code Playgroud)