Connection Class In Windows Form

Introduction:

In this article we will discuss the connection class in C# because in beginner’s level most student are clear about the inheritance but can’t use this approach in a professional project. Basically object-oriented programming solves  many issues and makes our programming more easier. After you read this article you'll have better knowledge about object-oriented programming

Step 1:

Now we start, first we create the Windows Form Based Project then after choosing Windows Form Project we press OK Button.

Button

Step 2:

After creating the project we add the class and change the name of the class and set the name as Connection Class. Left click on you project and add class and press add button.

Button

Step 3: Now we create the database in Microsoft Access 2013, setting the EmployeeDatabase and name the table Employee.

Employee

Step 4:

After creating the class we make some method in class, then we inherit this method in our program. First we add two namespaces in our program; if you are using Microsoft Access then add these two namespaces in your class. If you are using SQL Server then you add another two libraries which are similar to Microsoft Access, only change OLEDB to SQL.

code
code

Step 5:

Now we design the user interface to insert the employee information by dragging  and dropping some labels and textboxes and buttons:

form

Step 6:

Now double click on the save button  and now we don't need any open and closed connection, we only make instance of class and then use it.

code

Step 7:

Now we make the insert query and inherit all methods which we declare in class and use it:

code

  1. privatevoid button1_Click(object sender, EventArgs e)  
  2. {  
  3.         con = newConnectionClass();  
  4.         con.myoledbconnection();  
  5.         con.oledbquery("INSERT INTO Employee([Name],[Father_Name],[Department],[Email_Address],[Phone_Number])  
  6.             VALUES(@Name, @Father_Name, @Department, @Email_Address, @Phone_Number)  
  7.             ");  
  8.   
  9.             con.cmd.Parameters.AddWithValue("@Name", textBox1.Text).ToString(); con.cmd.Parameters.AddWithValue("@Father_Name", textBox2.Text).ToString(); con.cmd.Parameters.AddWithValue("@Department", textBox3.Text).ToString(); con.cmd.Parameters.AddWithValue("@Email_Address", textBox4.Text).ToString(); con.cmd.Parameters.AddWithValue("@Phone_Number", textBox5.Text).ToString();  
  10.   
  11.             con.nonqueryex(); MessageBox.Show("Data Is Save");  
  12.         }  
Step 8:

Now when you code on a button, then press the run button and put the information all and press the save button, all the information is saved in the employee table and you can see also in database table:

table

You see in the database the record is inserted in database as well: 

database

 

Ebook Download
View all
Learn
View all