Tuesday, February 18, 2014

Calculation using Asp.Net

Here I am going to explain ,How can you calculate arithmetic  details in asp.net.
Example : 3*4-68*(5+3). Here you can calculate all type of arithmetic  calculation.
In previous articles I explained How can you Rotate Image In Asp.Net ? ,
How to Print Images in Runtime Using ASP.Net .

Download Code Here




Step 1: Create a webpage (.aspx page)
Copy and paste the below code in <BODY> section  .

<body>
    <form id="form1" runat="server">

<asp:TextBox ID="txtcalculate" runat="server" Height="21px" Width="197px"></asp:TextBox><asp:RequiredFieldValidator 
        ID="RequiredFieldValidator1" runat="server" ControlToValidate="txtcalculate" 
        ErrorMessage="TextBox can not be empty"></asp:RequiredFieldValidator>
<br />
<asp:Label ID="lblmsg" runat="server" Text=""></asp:Label>

<br />

<asp:Button ID="btnEvaluate" runat="server" Text="Calculate" onclick="btnEvaluate_Click"
            />
        <br />

  Calculation Method, you can use *,+,-,/,(,) etc.>
  Example : 7+3*(4-2)
    
    </form>
    
</body>

Step 2 : Now Add Namespace 
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Drawing;

Step 2: Now go to the aspx.cs page  and
           Write the below code

public partial class _Default : System.Web.UI.Page 
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    public object calculate(string eqn)
    {
        DataTable dt = new DataTable();
        var result = dt.Compute(eqn, string.Empty);
        return result;
    }


    protected void btnEvaluate_Click(object sender, EventArgs e)
    {
        try
        {
            string result = Convert.ToString(calculate(txtcalculate.Text.Trim()));
            lblmsg.Text = "Your Result: " + result;
            lblmsg.ForeColor = Color.Green;
        }
        catch (Exception ex)
        {
            lblmsg.Text = ex.Message.ToString();
            lblmsg.ForeColor = Color.Red;
        }
    }
}

If this Program Help you, Please Share

No comments:

Post a Comment