Expression. DivideByZeroException.

3 posts, 0 answers
  1. Dominik
    Dominik avatar
    82 posts
    Member since:
    Dec 2012

    Posted 25 Jun 2013 Link to this post

    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. Maarten
    Maarten avatar
    1 posts
    Member since:
    Nov 2012

    Posted 25 Jun 2013 Link to this post

    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
  3. Dimitar
    Admin
    Dimitar avatar
    2907 posts

    Posted 25 Jun 2013 Link to this post

    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?
Back to Top