I was actually trying to explore how to work with tabs. It seemed pretty easy so I thought of venturing further and giving each of my tab-pages a meaningful look. And there it goes. I landed up building a small application which would help you in learning the different aspects of C# programming right from how to work with a user-control and to connect to a database which my first tab-page shows (and so does this article). In part2 of this article you would learn about datasets and about displaying data in a grid-control as has been done in the second tab-page. The last tab-page (and part3 of the article) will show you how to populate a treeview control with data that is placed in an XML file and is parsed by DOM. It is a very simple application but would certainly help beginners acquaint themselves with the basic concepts in C#.
In this article I would only concentrate on the first tab-page so you would learn about the use of a user-control and the details of database connectivity and record insertions.
As you can see, we have a screen displaying a simple form asking for the usual details of a person. I could have created the different controls (labels, textboxes shown on the screen) on the tabpage1 itself but I decided to create a separate class called EmployeeDataScreen that inherits from UserControl. The UserControl class helps you to create controls that can be used across a number of applications. It helps to give your applications a consistent look.
EmployeeDataScreen class a synopsis
In the EmployeeDataScreen class I have declared the controls, initialized them and added them to the layout (usual non-explanatory stuff). What is interesting and needs a little explanation is the functionality of Save_to_database button. As the name suggests it helps to save the record to the database. The code snippet is shown below:
private
void saveToDatabase(Object o, System.EventArgs e)
{
try
{
Initialize_member_variables ();
database_conn save_record = new database_conn();
save_record.connect_to_database();
String insert_rec= "Insert into emp_details (Emp_Name, Emp_Address, Emp_City, Emp_State, Emp_Pin, Emp_Country, Emp_Email)"+
" values('"+name+" ','"+address+" ','"+city+"',' "+state+"',' "+pin+" ',' "+country+"','"+email+"');";
save_record.insert_record(insert_rec);
save_record.close_connection();
}
catch(System.Exception exp)
{
MessageBox.Show("Error.."+exp.Message.ToString());
}
}
The function Initialize_member_variables () initializes the value in the textbox controls to the member variables defined in the class that then helps to construct the query (defined by the String insert_rec) to insert the record in the database.
You would notice that we have instantiated a class called database_conn.It is a class that deals with creating a connection with the database (done with the connect_to_database () method) inserting a record into the database (done with the insert_record (..) method and closing the connection as done with the close_connection() method.
We will soon study how these functions work.
There is another useful function called clear_data_in_controls () in the EmployeeDataScreen class that initializes the textbox controls with null values.
Let us see how we show the form on the tabpage.
Main application class a synopsis
In the main application class (Tab.cs), I have created a tabcontrol and three tabpages. I have then added the tabpages to the tabcontrol as shown below:
this
.tabControl1.Controls.AddRange(new System.Windows.Forms.Control[] {this.tabPage1,this.tabPage2,this.tabPage3});
I have then added an instance of EmployeeDataScreen class to tabPage1.
this
.tabPage1.Controls.Add(this.emp_control);
So, the entire data entry form (defined in the EmployeeDataScreen class) gets inserted in the tabpage.
Further I have added an event handler to the tabcontrol as shown.
this
.tabControl1.SelectedIndexChanged += new System.EventHandler (this.OnChange);
So whenever you move between the tabpages the handler gets triggered and calls the OnChange event. The code for which is shown below:
private
void OnChange(Object o, System.EventArgs e)
{
TabControl ctrl = (TabControl)o;
int x = ctrl.SelectedIndex;
switch(x)
{
case 0:
clear_emp_form();
break;
case 1:
show_emp_grid();
break;
case 2:
displayTreeView();
break;
default :
break;
}
}
For the first tabpage it calls a function clear_emp_form () that in turn calls the clear_data_in_controls () function of the EmployeeDataScreen class that re-initializes the textbox values to null.
The next two functions will also become clear when we study about tabpage2 and tabpage3.
The button called cancel as seen on the form closes the window (or the form) by calling Application.Close () method on the button click event handler.
The database connectivity class (database_conn) a synopsis
Now let us see how the database connectivity has been done and how is the record getting added to the database when the save_to_database button is clicked.
I have created a separate class called database_conn () to handle database connectivity. I have used the Access2000 database and created a database by the name of employee and a table called emp_details.
The code for the functions connect_to_database (), insert_record (..) and close_connection() is shown below.
public
void connect_to_database()
{
try
{
OleDbConnection connection = new OleDbConnection (@"Provider=Microsoft.Jet.OLEDB.4.0;" +
@"Data Source=..\\..\\data\\employee.mdb;" +
@"UserId=;Password=;");
connection.Open();
}
catch(Exception exp)
{
MessageBox.Show("Error in connecting to the database"+exp.Message);
}
}
public void insert_record(String insert_rec)
{
try
{
OleDbCommand command = new OleDbCommand(insert_rec,connection);
command.ExecuteNonQuery();
}
catch(Exception exp)
{
MessageBox.Show("Error in inserting record"+exp.Message);
}
}
public void close_connection()
{
if (connection.State == ConnectionState.Open)
connection.Close();
}
Note that you have to use the namespace System.Data.OleDB for accessing data from the Access database. It contains a set of classes for doing the different tasks. In order to connect to the database you create an instance of OleDbConnection. In that you pass the driver name that helps you to connect to the database, the name of the database to connect to and the optional username and password parameters. If the parameters passed are incorrect a runtime exception is thrown. If valid then you call the Open () method to open a connection with the datasource.
Once the connection is established you can do the database operations like Insert, Select, Delete etc. In the method insert_record (..) I will show you how to insert a record in the database. You need to create an instance of the OleDBCommand object passing the SQL query and connection object as the parameters.
The OleDBCommand object represents the SQL statement to be executed against the database. For the Insert, Delete, Update statements we use the ExecuteNonQuery () method to execute the statements.
Finally the function close_connection () calls the Close () function on the connection object to close the database. This method is only called if the connection had been open. (This is verified using the State property of the connection object that returns the current state of the connection).
Conclusion:
Hope this article will give a novice a good boast in database connectivity and would keep him interested in learning as to what happens in tabpage2 and tabpage3.