This blog explains -

It also covers the the following System Test question,
  1. Create a class for the math ( "+","-") operations -- name the class "MathOp".
  2. Extend the class using inheritance to include ("*","/") name the class "MathOp2".
  3. Create the following class/function when select a line from the list box, the user should be able to modify the values/operations and save it to the listbox/database Let’s say the user clicked on “1+3=4” , the values 1,3 should be displayed in the input text boxes.

Step 1: At DataBase.

I use the following table to demonstrate the above concepts.

  1. Create table MathRresults(
  2. ID int primary key identity(1,1),
  3. Result varchar(20)
  4. )
Application

Step 2: Creating the project.

Now create the project using the following.

Go to Start, then All Programs and click Microsoft Visual Studio 2010.

Go to File, then click New, Project..., Visual C# , Web. Then select ASP.NET Empty Web Application.

Provide the project a name and specify the location.

Empty Web Application
Step 3 : Web.Config.

Create the connection string in the Web.Config file as in the following code snippet:
  1. <connectionStrings>
  2. <add name="conStr"
  3. connectionString="Password= 1234; User ID=sa; Database=DB_Jai; Data Source=."
  4. providerName="System.Data.SqlClient"/>
  5. </connectionStrings>
Next: Right-click on Solution Explorer and add a web form to your project.
Make your .aspx as follows -

calculation

Step 4 : JavaScript Validations.

Use the following code to validate the textboxes.
  1. < script type = "text/javascript" > function Valid()
  2. {
  3. if (document.getElementById('<%=txtFirstNumber.ClientID%>').value.trim() == "") {
  4. var msg = document.getElementById('<%=lblMsg.ClientID %>');
  5. msg.innerHTML = "Please enter First Number";
  6. msg.style.color = "red";
  7. document.getElementById('<%=txtFirstNumber.ClientID%>').focus();
  8. return false;
  9. }
  10. if (document.getElementById('<%=txtSecondNumber.ClientID%>').value.trim() == "") {
  11. var msg = document.getElementById('<%=lblMsg.ClientID %>');
  12. msg.innerHTML = "Please enter Second Number";
  13. msg.style.color = "red";
  14. document.getElementById('<%=txtSecondNumber.ClientID%>').focus();
  15. return false;
  16. }
  17. }
  18. < /script>
CodeBehind
Add the following namespaces:
  1. using System.Data;
  2. using System.Data.SqlClient;
  3. using System.Configuration;
Invoke the ConnectionString from Web.Config as in the following:
  1. SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConStr"].ConnectionString);
Step 5 : Declare global variables.
  1. private Decimal Num1;
  2. private Decimal Num2;
  3. string constr = ConfigurationManager.ConnectionStrings["connectionStr"].ConnectionString;
Step 6: Classes and Inheritance.

MathOp class Contains two methods that are Add, Subtract.

MathOp2 class Contains two methods that are Mul, Div.
  1. public class MathOp
  2. {
  3. public Decimal Add(Decimal value1, Decimal value2)
  4. {
  5. return (value1 + value2);
  6. }
  7. public Decimal Subtract(Decimal value1, Decimal value2)
  8. {
  9. return (value1 - value2);
  10. }
  11. }
  12. public class MathOp2: MathOp
  13. {
  14. public Decimal Mul(Decimal value1, Decimal value2)
  15. {
  16. return (value1 * value2);
  17. }
  18. public Decimal Div(Decimal value1, Decimal value2)
  19. {
  20. return (value1 / value2);
  21. }
  22. }
Step 7: User defined methods.
  1. //Clear () method is used to clear the textbox box values.

  2. private void Clear()
  3. {
  4. txtFirstNumber.Text = string.Empty;
  5. txtSecondNumber.Text = string.Empty;
  6. lblResult.Text = string.Empty;
  7. lblMsg.Text = string.Empty;
  8. }
  9. //saveResult() method is used to save the result sets in database.
  10. private void saveResult()
  11. {
  12. SqlConnection con = new SqlConnection(constr);
  13. SqlCommand cmd = new SqlCommand("insert into MathRresults values('" + lblResult.Text + "')", con);
  14. SqlDataReader dbr;
  15. try
  16. {
  17. con.Open();
  18. dbr = cmd.ExecuteReader();
  19. lblMsg.Text = "Values saved Successfully";
  20. lblMsg.ForeColor = Color.Green;
  21. dbr.Read();

  22. }
  23. catch (Exception ex)
  24. {
  25. lblMsg.Text = "Failed to Save because :" + ex;
  26. lblMsg.ForeColor = Color.Red;
  27. }
  28. con.Close();
  29. BindResultsToListview();
  30. }

  31. // UpdateResult() method is used to update the result sets with existing records in database.

  32. private void UpdateResult()
  33. {
  34. int ? id = null;
  35. foreach(ListItem li in ListBox1.Items)
  36. {
  37. if (li.Selected == true)
  38. {
  39. id = Convert.ToInt32(ListBox1.SelectedValue);
  40. }
  41. }
  42. SqlConnection con = new SqlConnection(constr);
  43. SqlCommand cmd = new SqlCommand("Update MathRresults set Result = '" + lblResult.Text + "' Where ID = '" + id + "'", con);
  44. SqlDataReader dbr;
  45. try
  46. {
  47. con.Open();
  48. dbr = cmd.ExecuteReader();
  49. lblMsg.Text = "Values Updated Successfully";
  50. lblMsg.ForeColor = Color.Green;
  51. dbr.Read();
  52. //while (dbr.Read())
  53. //{
  54. //}
  55. }
  56. catch (Exception ex)
  57. {
  58. lblMsg.Text = "Failed to update because:" + ex;
  59. lblMsg.ForeColor = Color.Red;
  60. }
  61. finally
  62. {
  63. con.Close();
  64. BindResultsToListview();
  65. }
  66. }

  67. //BindResultsToListview Method is used to bind the operations to ListBox.

  68. private void BindResultsToListview()
  69. {
  70. Clear();
  71. SqlConnection con = new SqlConnection(constr);
  72. string cmd = "Select Id, Result from MathRresults";
  73. SqlDataAdapter adpt = new SqlDataAdapter(cmd, con);
  74. DataSet ds = new DataSet();
  75. adpt.Fill(ds, "MathRresults");
  76. DataTable myDataTable = ds.Tables[0];
  77. if (ds.Tables.Count > 0 && ds != null && ds.Tables[0].Rows.Count > 0) {
  78. ListBox1.DataSource = ds;
  79. ListBox1.DataValueField = "ID";
  80. ListBox1.DataTextField = "Result";
  81. ListBox1.DataBind();
  82. }
  83. }

  84. //DeleteFromListView is used to delete the selected item in ListBox.

  85. private int DeleteFromListView(int id)
  86. {
  87. //Here using statement is automatically close the connections
  88. using(SqlConnection con = new SqlConnection(constr))
  89. {
  90. SqlCommand cmd = new SqlCommand("delete from MathRresults where id = " + id + "", con);
  91. con.Open();
  92. cmd.ExecuteNonQuery();
  93. return 0;
  94. }
  95. }

Step 8 : Page load.

Copy the following code in page_ load.
  1. if (!Page.IsPostBack)
  2. {
  3. BindResultsToListview();
  4. }
  5. Clear();
  6. //txtFirstNumber value to be assigned to Num1 variable.
  7. Num1 = Convert.ToDecimal(txtFirstNumber.Text);
  8. //txtSecondNumber value to be assigned to Num2 variable.
  9. Num2 = Convert.ToDecimal(txtSecondNumber.Text);

Step 9: Addition.

To add or update two values and save the result set in database –
  1. protected void btnAdd_Click(object sender, EventArgs e)
  2. {
  3. MathOp2 m = new MathOp2();
  4. Decimal additon = m.Add(Num1, Num2);
  5. lblResult.Text = (Num1 + ("+" + (Num2 + ("=" + additon))));
  6. lblResult.ForeColor = Color.Green;
  7. //this is pretty simple
  8. //if your not selected any item in listbox it's save your result as a new record in database.
  9. //if your selected any item in listbox it's update your result with existing record in database.

  10. if (ListBox1.SelectedValue == string.Empty)
  11. {
  12. saveResult();
  13. }
  14. else
  15. {
  16. UpdateResult();
  17. }
  18. }
Step 10: Subtraction.

To Subract values and save the result set in database –
  1. protected void btnSubtract_Click(object sender, EventArgs e)
  2. {
  3. MathOp2 m = new MathOp2();
  4. Decimal subtraction = m.Subtract(Num1, Num2);
  5. lblResult.Text = (Num1 + ("-" + (Num2 + ("=" + subtraction))));
  6. lblResult.ForeColor = Color.Green;
  7. if (ListBox1.SelectedValue == string.Empty) saveResult();
  8. else UpdateResult();
  9. }
Step 11: Multiplication.

To multipliy two values and save the result set in database -
  1. protected void btnMultiply_Click(object sender, EventArgs e)
  2. {
  3. MathOp2 m = new MathOp2();
  4. Decimal division = m.Mul(Num1, Num2);
  5. lblResult.Text = (Num1 + ("*" + (Num2 + ("=" + division))));
  6. lblResult.ForeColor = Color.Green;
  7. if (ListBox1.SelectedValue == string.Empty) saveResult();
  8. else UpdateResult();
  9. }
Step 12 : Division.

For division of two values and save the result set in database -
  1. protected void btnDivide_Click(object sender, EventArgs e)
  2. {
  3. // if txtSecondNumber value is zero, then the result would be infinite.
  4. // To prevent that make one alert for user that "Divide By Zero is Invalid"
  5. if (Num2 == 0)
  6. {
  7. lblMsg.Text = "Divide By Zero is Invalid";
  8. lblMsg.ForeColor = Color.Red;
  9. return;
  10. }
  11. MathOp2 m = new MathOp2();
  12. Decimal division = m.Div(Num1, Num2);
  13. lblResult.Text = (Num1 + ("/" + (Num2 + ("=" + division))));
  14. lblResult.ForeColor = Color.Green;
  15. if (ListBox1.SelectedValue == string.Empty) saveResult();
  16. else UpdateResult();
  17. }
Step 13 : Delete the selected listbox value.

To delete the selected item from listbox as well as database –
  1. protected void btnDelete_Click(object sender, EventArgs e)
  2. {
  3. lblResult.Text = string.Empty;
  4. lblMsg.Text = string.Empty;
  5. for (int i = 0; i <= ListBox1.Items.Count - 1; i++)
  6. {
  7. if (ListBox1.Items[i].Selected != false)
  8. {
  9. DeleteFromListView(Convert.ToInt32(ListBox1.Items[i].Value));
  10. }
  11. }
  12. ListBox1.Items.Clear();
  13. BindResultsToListview();
  14. lblMsg.Text = "Selected Value deleted successfully";
  15. }

  16. // ListBox1_SelectedIndexChanged

  17. protected void ListBox1_SelectedIndexChanged(object sender, EventArgs e)
  18. {
  19. lblMsg.Text = string.Empty;
  20. if (ListBox1.SelectedValue == string.Empty)
  21. {
  22. return;
  23. }
  24. int ? id = null;
  25. string selectedtext = null;
  26. foreach(ListItem li in ListBox1.Items)
  27. {
  28. if (li.Selected == true)
  29. {
  30. id = Convert.ToInt32(ListBox1.SelectedValue);
  31. }
  32. }

  33. SqlConnection con = new SqlConnection(constr);
  34. SqlDataAdapter adpt = new SqlDataAdapter("Select * from MathRresults Where Id = '" + id + "'", con);
  35. DataSet ds = new DataSet();
  36. adpt.Fill(ds, "MathRresults");
  37. DataTable myDataTable = ds.Tables[0];

  38. if (ds.Tables.Count > 0 && ds != null && ds.Tables[0].Rows.Count > 0)
  39. {
  40. selectedtext = ds.Tables[0].Rows[0]["Result"].ToString();
  41. }

  42. //Split the item by the operator and the '=' into an array of strings

  43. string[] parts = selectedtext.Split('+', '-', '*', '/', '=');
  44. if (parts.Length > 2) {
  45. //Define a variable for each part
  46. string part1 = parts[0].Trim();
  47. string part2 = parts[1].Trim();
  48. string part3 = parts[2].Trim();
  49. txtFirstNumber.Text = part1;
  50. txtSecondNumber.Text = part2;
  51. lblResult.Text = part3;
  52. }
  53. }

I hope you enjoyed it.