Designing A Winform In C# And Linking It To A SQL Server Database

The main objective of windows basedprogramming is to create applications that are linked to databases,have user-friendly interface (windows forms) and are capable of runningon most platforms. C# language has all these capabilities to createapplications that are mostly required by the programmers at the time ofdesigning the interface and coding the modules of their projects. SinceC# is object oriented (where each entity is considered as object andwhere terminologies like abstraction, encapsulation, polymorphism, andinheritance prevails the language paradigm), most of the high levelprogrammers feels easy to code the program in the form of classes andto reuse them in their later code.

This article will teach you how to designan interface (Windows Form) in Visual Studio .NET using the language ofC# and then creating and linking it to a database on SQL Server 2000.The first thing to be done is to start the Visual Studio .NETenvironment and create a new Project named "WindowsApplication1". Theprojects by default are usually saved in "My Documents\Visual StudioProjects" folder but you can browse and change the location. Nextchoose the Project Types as: Visual C# Projects and Templates: WindowsApplication and click OK. Now a new project for you has been created.You can add as many forms you like from the Project —> Add WindowsForms, but here we need only two forms. The Form1 is designed throughthe Toolbox components as follows. The View —> Toolbox containsWindows components like Labels, Text box, Combo box, Buttons, Radio andCheck box, Picture box, List box, Timer, Progress bar, Main Menu,DataGrid and other controls. You just need to drag these on the formand set their properties. All the code for the above additions will beautomatically generated by the .NET compiler. An example picture of theForm1 to be designed for this tutorial is shown below:

                                Figure 1: FORM1 DESIGN

Form2 will only contain the DataGridComponent from the Toolbox. You can set the Color, Name, Font and otherproperties through the Properties of the forms. Here I have set theBackground color to Blue.

Now move towards designing the database.This database is a simple database for registering people to use anyemail service. Start the Enterprise Manager of the SQL Server 2000 andcreate new database named "REGISTER DATABASE". Within the database,create new table named "REGISTER" in which following columns andattributes are defined while designing:

COLUMN NAME

DATA TYPE

LENGTH

ALLOW NULLS

ID

int

4

No

FNAME

varchar

50

No

LNAME

varchar

50

No

LANG

char

30

Yes

COUNTRY

char

30

Yes

STATE

char

30

Yes

ZIPCODE

int

4

Yes

TIMEZONE

char

30

Yes

GENDER

char

30

Yes

BDAY

int

4

Yes

BMONTH

char

30

Yes

BYEAR

int

4

Yes

OCCUPATION

varchar

50

Yes

Now the next step is to link this databasewith our Windows Application. Go back to Form1 and drag theSqlConnection and SqlDataAdapter components from theToolbox—->Data bar. Double click on the form to go the code. Thenamespaces at the above of your program should contain these:

using System;

using System.Drawing;

using System.Collections;

using System.ComponentModel;

using System.Windows.Forms;

using System.Data;

using System.Data.SqlClient;

Allthe SqlConnection, SqlCommand, SqlDataAdapter etc are inherited fromSystem.Data.SqlClient. Next create new variables for storing the valuesretrieved from the textboxes and combo boxes keyed in by the user whilefilling out the form. For example we declare the following:

private string Fname,Lname,Lang,Country,State,Timezone,

Bmonth,Byear,Occup;

private char Gender;

private int Zipcode,Bday;

Then we retrieve all that is keyedin by the user by the component events. For every component i.e. textboxes, combo boxes and radio boxes that we created, write the followingcode:

private void textBox1_TextChanged(object sender, System.EventArgs e)

{

this.Fname=this.textBox1.Text.ToString();

}

private void comboBox1_SelectedIndexChanged(object sender, System.EventArgs e)

{

this.Lang=this.comboBox1.SelectedItem.ToString();

}

private void radioButton1_CheckedChanged(object sender, System.EventArgs e)

{

this.Gender='M';

}

Now add the following code to make the buttons functional in their click event code:

private void button1_Click(object sender, System.EventArgs e)

{ //LIST ALL REGISTERIES BUTTON

Form2 f2=new Form2();

f2.ShowDialog();

}

private void button2_Click(object sender, System.EventArgs e)

{ //CANCEL BUTTON

this.Dispose();

}

private void button3_Click(object sender, System.EventArgs e)

{ //REGISTER NOW BUTTON

if(this.textBox1.Text==""||this.textBox2.Text=="")

s="smallblack"> MessageBox.Show("Please enter your name");

else

{this.sqlConnection1.Open();

stringinsert="INSERT INTO REGISTER(FNAME, LNAME, LANG, COUNTRY, STATE,ZIPCODE, TIMEZONE, GENDER, BDAY, BMONTH, BYEAR, OCCUPATION) VALUES ('"+this.Fname +"','"+ this.Lname +"','"+ this.Lang +"','"+ this.Country +"','"+ this.State +"','"+ this.Zipcode +"','"+ this.Timezone +"','"+ this.Gender +"','"+ this.Bday +"','"+ this.Bmonth +"','"+ this.Byear +"','"+ this.Occup +"')";

SqlCommand cmd=new SqlCommand(insert,this.sqlConnection1);

cmd.ExecuteNonQuery();

this.sqlConnection1.Close();

MessageBox.Show("You have been successfully registered to our database.");

}

}

Now we go to the Form2. We havealready set a DataGrid in the form. Also drag the SqlConnection andSqlDataAdapter components same as before and add the following code inthe Form2_Load event method:

private void Form2_Load(object sender, System.EventArgs e)

{

string select="SELECT * FROM REGISTER";

DataSet ds=new DataSet();

this.sqlConnection1.Open();

this.sqlDataAdapter1=new SqlDataAdapter(select,sqlConnection1);

this.sqlDataAdapter1.Fill(ds,"REGISTER");

if(ds.Tables["REGISTER"].Rows.Count==0)

{

MessageBox.Show("There are currently no registries in the database.");

}

else

{

this.dataGrid1.SetDataBinding(ds,"REGISTER");

}

this.sqlConnection1.Close();

}

The form2 after running the program and registering a user "Fatima Ahmed" will look like this:

Hope this article helps you learn all what is taught about creating, designing a Winform in C# and linking it to a database.

<!– start a block of source code –>

Downloads

<!– demo and source files –>

Download demo project – 138 KB

Twitter Digg Delicious Stumbleupon Technorati Facebook Email

One Response to “Designing A Winform In C# And Linking It To A SQL Server Database”

  1. This is fantastic lesson. Since last two days i was searching on net about such , but failed in so, i leared a lot from it.
    i would appreciate if i can contact writer by email, so that i can learn more.
    i request writer of this lesson please do contact me on this email address.

    Thanks n Rgds