System Test in Interview on ListBox

This blog explains -

  • How to use classes and inheritance.
  • CRUD operations with listbox using databse.
  • How to use split function.
  • How to validate the textboxes using javascript.
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.  
  10. //saveResult() method is used to save the result sets in database.
  11.  
  12. private void saveResult()  
  13. {  
  14.     SqlConnection con = new SqlConnection(constr);  
  15.     SqlCommand cmd = new SqlCommand("insert into MathRresults values('" + lblResult.Text + "')", con);  
  16.     SqlDataReader dbr;  
  17.     try  
  18.     {  
  19.         con.Open();  
  20.         dbr = cmd.ExecuteReader();  
  21.         lblMsg.Text = "Values saved Successfully";  
  22.         lblMsg.ForeColor = Color.Green;  
  23.         dbr.Read();  
  24.        
  25.     }  
  26.     catch (Exception ex)  
  27.     {  
  28.         lblMsg.Text = "Failed to Save because :" + ex;  
  29.         lblMsg.ForeColor = Color.Red;  
  30.     }  
  31.     con.Close();  
  32.     BindResultsToListview();  
  33. }  

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

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

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

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

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

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


Step 8 : Page load.

Copy the following code in page_ load. 
  1. if (!Page.IsPostBack)    
  2. {    
  3.    BindResultsToListview();    
  4. }  
  5.   
  6. Clear();   
  7.   
  8. //txtFirstNumber value to be assigned to Num1 variable.    
  9.     Num1 = Convert.ToDecimal(txtFirstNumber.Text);   
  10. //txtSecondNumber value to be assigned to Num2 variable.    
  11.     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.  
  8.     //this is pretty simple  
  9.     //if your not selected any item in listbox it's save your result as a new record in database.  
  10.     //if your selected any item in listbox it's update your result with existing record in database.  
  11.    
  12.     if (ListBox1.SelectedValue == string.Empty)  
  13.     {  
  14.         saveResult();  
  15.     }   
  16.     else   
  17.     {  
  18.         UpdateResult();  
  19.     }  
  20. }  
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.     MathOp2 m = new MathOp2();  
  3.     Decimal division = m.Mul(Num1, Num2);  
  4.     lblResult.Text = (Num1 + ("*" + (Num2 + ("=" + division))));  
  5.     lblResult.ForeColor = Color.Green;  
  6.     if (ListBox1.SelectedValue == string.Empty) saveResult();  
  7.     else UpdateResult();  
  8. }  
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. // ListBox1_SelectedIndexChanged 

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

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

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

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

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


I hope you enjoyed it.