How to Establish Relationship Between Tables in an ASP.Net Web Application

Introduction

In this article I am creating an ASP.NET Web Application showing relationships among Countrys, States and Cities. I am using ADO.NET to connect SQL Server with ASP.NET. I am creating this application because I think it will be very helpful to you. There are many basic programmers who do not know how to create and display a relationship among a Country, States of that Country and Cities of that State. Friends, If you do not understand me then just proceed for now and at the end of the article you will get my message.

If we have three dropdownlists for each of Country, State and City and we want that when we select a Country like India then the States belonging to that Country will populate the second dropdownlist (suppose Uttaranchal), similarly if we select any State then the Cities of that State will populate the third dropdownlist. Please view the following snapshot for help:

final.jpg

Prerequisites

There are the following prerequisites for creating this application:

  • Visual Studio (Front End)
  • SQL Server (Back End)
  • ADO.NET   (For Connectivity)

Create Database

Let's create a database in which three tables are created and also create a relationship among them. I am creating this database in SQL Server 2012. Let's understand this step-by-step.

Note: You must know the Constraints like Primary Key and Foreign Key, that are very useful for creating a relationship among tables.  

Step 1: Open SQL Server (any version).

Step 2: In the New Query wizard:

NewQuery.jpg

Step 3: Create a database with the following command:

CREATE DATABASE SampleDB

Step 4: Create tables with the names Tbl_Country, Tbl_State and Tbl_City.

  1. Country Table
     

    USE SampleDB

     

    CREATE TABLETbl_Country

    (

           PKCountry_IDint primarykey identity(1,1),

           Country_Namevarchar(50)

    )


    Insert values into this table, after inserting:

    Tbl_Country.jpg
     

  2. State Table

    Let's create this table with the following procedure.

    Step 1: Go to Object Explorer, expand your database and right-click on "Tables" for creating a new table.

    NewTable.jpg

    Step 2: Design the table with the fields PKState_ID (Primary Key), FKCountry_ID and State_Name and before saving the table follow the instructions given below.
     

    1. In the design wizard, right-click on the FKCountry_ID column for creating a relationship.

      Relationship-in-State.jpg

      Note: Ensure that you created the FKCountry_ID column as a Primary Key in the Tbl_Country Table. The column name may differ but the values should be the same.
       
    2. After you the click on "Relationships", the following wizard will open. Click on "Add".

      AddFK-in-State.jpg
       
    3. After clicking on Add provide the name of the Identity (optional) and click on "Tables And Columns Specific" as in the following:

      AddFK1-in-State.jpg
       
    4. In the next Tables and Columns wizard, Select Tbl_Country as a Primary Key Table and select PKCountry_ID as a Primary Key column in the columns in the left pane and in the right pane select FKCountry_ID as a Foreign Key column as in the following.

      Tables&Columns-in-State.jpg

      Click on OK.
       
    5. In the next wizard, Click "Close".

      AddFK2-in-State.jpg
       
    6. Save your table and provide the table name.

      Save-in-State.jpg
       
    7. When you click on "Save", the Save wizard will open. Ignore the warning and click "Yes".

      Save1-in-State.jpg
       
    Step 3: Insert values into the State table as in the following:

    Tbl_State.jpg
     
  3. City Table

    Create this table using the following procedure.

    Step 1: Create a new table with design view as I mentioned in the previous Step 1.

    Step 2: Design the table with the fields PKCity_ID (Primary Key), FKState_ID, City_Name and before saving the table use the following instructions.
     
    1. In the design wizard, right-click on the FKState_ID column to create the relationship.

      Relationship-in-City.jpg

      Note: Ensure that you have created the FKState_ID column as a Primary Key in the Tbl_State Table. The column name may differ but the values should be the same.
       
    2. After you the click on Relationships, a wizard will open. Click on "Add".
       
    3. Provide the name of Identity (optional) and click on "Tables And Columns Specific" as in the following.

      AddFK1-in-City.jpg
       
    4. In the next Tables and Columns wizard, select Tbl_State as a Primary Key of the table and select PKState_ID as a Primary Key column in the columns in the left pane and in the right pane select FKState_ID as a Foreign Key column as in the following:

      Tables&Columns-in-City.jpg

      Click on "OK".
       
    5. In the next wizard, click "Close".

      AddFK2-in-City.jpg
    6.    
    7. Save your table and provide the table name.

      Save-in-City.jpg
       
    8. When you click on "Save", the Save wizard will open. Ignore the warning and click on "Yes".

      Save1-in-City.jpg
       
    Step 3: Insert values into the City table as in the following:

    Tbl_City.jpg    

    Tbl_City2.jpg  

Create an application on Visual Studio

Let's create an ASP.NET Web Application using ADO.NET for connectivity with the database. I am creating this application with 2-tier architecture on Visual Studio 2013 Preview. Let's create this application step-by-step.

Step 1: "File" -> "New" -> "Project..."

Step 2: Select "ASP.NET Web Application" then provide the application name.

NewProject.jpg

Step 3: Select "Empty Project Template" to create this application.

EmptyTemplate.jpg

Step 4: In the Solution Explorer, right-click on your project and go to "Add" > "New Item".

Step 5: Select "Web Form" then enter a web form name.

webform.jpg

Step 6: Design your front-end page with the following source:

<form id="form1" runat="server">

    <table align="center" style="height: 230px; width: 362px">

        <tr>

            <td colspan="2" style="font-size: x-large; text-align: center;">Welcome to CSC</td>

        </tr>

        <tr>

            <td class="auto-style1" style="font-size: large">Country</td>

            <td><asp:DropDownList ID="DDLCountry" runat="server" AutoPostBack="false" OnSelectedIndexChanged="DDLCountry_SelectedIndexChanged" Height="22px"></asp:DropDownList></td>

        </tr>

        <tr>

            <td class="auto-style1" style="font-size: large">State</td>

            <td><asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="false" OnSelectedIndexChanged="DDLState_SelectedIndexChanged" Height="22px" Width="122px"></asp:DropDownList></td>

        </tr>

        <tr>

            <td class="auto-style1" style="font-size: large">City</td>

            <td><asp:DropDownList ID="DropDownList2" runat="server" Height="22px" Width="122px"></asp:DropDownList></td>

        </tr>

    </table>

</form>

Define the following source in the "<head>":

<style type="text/css">

        .auto-style1 {

            width: 145px;

        }

</style>

 

cscform.jpg

 

Step 7: In the Solution Explorer right-click on your project and go to "Add" > "New Item".

 

Step 8: Select "Class", enter a class name.

 

dal.jpg

 

Step 9: Design your DAL class with the following code:

 

using System.Data;

using System.Data.SqlClient;

 

namespace CSCRelationshipApp

{

    public class DAL

    {

        SqlConnection con = new SqlConnection("Data Source=MCNDESKTOP44; Initial Catalog=SampleDB; User ID=YOUR USERNAME; Password=YOUR PASSWORD");

        SqlCommand cmd;

        SqlDataAdapter adap;

        DataTable dt;

 

        public DataTable Get_Country()

        {

            adap = new SqlDataAdapter("Select * from Tbl_Country",con);

            dt = new DataTable();

            adap.Fill(dt);

            return dt;

        }

 

        public DataTable Get_State(int Country_ID)

        {

            adap = new SqlDataAdapter("Select * from Tbl_State where FKCountry_ID=" + Country_ID + "", con);

            dt = new DataTable();

            adap.Fill(dt);

            return dt;

        }

 

        public DataTable Get_City(int State_ID)

        {

            adap = new SqlDataAdapter("Select * from Tbl_City where FKState_ID=" + State_ID + "", con);

            dt = new DataTable();

            adap.Fill(dt);

            return dt;

        }

    }

}

Step 10: Design your CSCForm.cs class with the following code:

 

namespace CSCRelationshipApp

{

    public partial class CSCForm : System.Web.UI.Page

    {

        DAL ObjDal = new DAL();

        protected void Page_Load(object sender, EventArgs e)

        {

            if (!IsPostBack)

            {

                Fill_Country();

            }

        }

 

        public void Fill_Country()

        {

            DDLCountry.DataSource = ObjDal.Get_Country();

            DDLCountry.DataTextField = "Country_Name";

            DDLCountry.DataValueField = "PKCountry_ID";

            DDLCountry.DataBind();

            DDLCountry.Items.Insert(0, new ListItem("--Select--", "0"));

        }

 

        public void Fill_State()

        {

            DDLState.DataSource = ObjDal.Get_State(Convert.ToInt32(DDLCountry.Text));

            DDLState.DataTextField = "State_Name";

            DDLState.DataValueField = "PKState_ID";

            DDLState.DataBind();

            DDLState.Items.Insert(0, new ListItem("--Select--", "0"));

        }

 

        public void Fill_City()

        {

            DDLCity.DataSource = ObjDal.Get_City(Convert.ToInt32(DDLState.Text));

            DDLCity.DataTextField = "City_Name";

            DDLCity.DataValueField = "PKCity_ID";

            DDLCity.DataBind();

            DDLCity.Items.Insert(0, new ListItem("--Select--", "0"));

        }

 

        protected void DDLCountry_SelectedIndexChanged(object sender, EventArgs e)

        {

            Fill_State();

        }

 

        protected void DDLState_SelectedIndexChanged(object sender, EventArgs e)

        {

            Fill_City();

        }

  

    }

}

Step 11: All done. Now debug.

final.jpg

Summary

So far in this article we saw how to create and relate Country, State and City from a Drop Down List in an application. I used Visual Studio 2013 Preview for the Front End and SQL Server 2012 for the Back End. I am sure that this article will help for creating and showing relationships among Country, State and City. So, just go for it and let me know if you have any problem regarding the development.

Don't forget to comment.

Up Next
    Ebook Download
    View all
    Learn
    View all