This is a migrated thread and some comments may be shown as answers.

Expression. DivideByZeroException.

2 Answers 159 Views
GridView
This is a migrated thread and some comments may be shown as answers.
konrad
Top achievements
Rank 1
konrad asked on 25 Jun 2013, 10:58 AM
Hi,

To reproduce problem just add 3 columns to grid and paste code below to Load event.

private void Form1_Load(object sender, EventArgs e)
{
    DataTable dt = new DataTable();
    dt.Columns.Add("d1", typeof(Decimal));
    dt.Columns.Add("d2", typeof(Decimal));
 
    dt.Rows.Add(new object[] { 3, 4 });
    dt.Rows.Add(new object[] { 1, 4 });
    dt.Rows.Add(new object[] { 0, 3 });
    dt.Rows.Add(new object[] { 3, 3 });
 
    radGridView1.Columns[0].FieldName = "d1";
    radGridView1.Columns[0].HeaderText = "d1";
    radGridView1.Columns[0].Name = "d1";
 
    radGridView1.Columns[1].FieldName = "d2";
    radGridView1.Columns[1].HeaderText = "d2";
    radGridView1.Columns[1].Name = "d2";
 
    radGridView1.Columns[2].HeaderText = "exp";
 
    radGridView1.DataSource = dt;
 
    radGridView1.Columns[2].Expression = "IIF(d1 = 0, 0, d2 / d1 )";
}

Even if we apply the condition that checks divide by zero, program will trow error:
A first chance exception of type 'System.DivideByZeroException' occurred in mscorlib.dll 

I was able to fool the "Expression" by double condition like this:

radGridView1.Columns[2].Expression = "IIF(d1 = 0, 0, d2 / (IIF(d1 = 0, 9999 , d1)))";




2 Answers, 1 is accepted

Sort by
0
Maarten
Top achievements
Rank 1
answered on 25 Jun 2013, 02:04 PM
Hi,

If possible, you should use a Case, like 

"CASE WHEN d1 = 0 THEN 0 ELSE d2 / d1 END"

IIF always evaluates both sides.

Cheers
Maarten
0
Dimitar
Telerik team
answered on 25 Jun 2013, 05:52 PM
Hi Dominik,

Thank you for writing.

To avoid the described behavior you can create a custom function like this:
public class CustomExpressionContext : Telerik.Data.Expressions.ExpressionContext
{
    /// <summary>
    /// My custom function, 
    /// </summary>
    /// <returns></returns>
    public decimal CustomDivide(decimal d1, decimal d2)
    {
        if (d1 == 0m)
        {
            return 0m;
        }
        else
        {
            return d2 / d1;
        }
    }
}

Then attach the function in the expression string like this:

Telerik.Data.Expressions.ExpressionContext.Context = new CustomExpressionContext();
this.radGridView1.Columns[2].Expression = "CustomDivide(d1, d2)"

I hope this helps. Should you have any other questions do not hesitate to ask. Regards,
Mitko
Telerik
RadChart for WinForms is obsolete. Now what?
Tags
GridView
Asked by
konrad
Top achievements
Rank 1
Answers by
Maarten
Top achievements
Rank 1
Dimitar
Telerik team
Share this question
or