Showing posts with label AJAX. Show all posts
Showing posts with label AJAX. Show all posts

Friday, January 4, 2013

Cascading Dropdown List for Country/State/City in ASP.Net using Entity Framework


In this blog I am going to show how we can work with cascading dropdown list for country/state/city in asp.net using Entity Framework.


Create three tables as per our need
CREATE TABLE country
  (
     countryID     INT NOT NULL,
     countryName   varchar(50) NOT NULL,
     PRIMARY KEY (countryID ),
  );
CREATE TABLE state
  (
 stateID     INT NOT NULL,
 countryID INT NOTNULL,
 stateName   varchar(50) NOT NULL,
 PRIMARY KEY (stateID ),
 FOREIGN KEY (countryID ) REFERENCES country (countryID));

CREATE TABLE city
  (
cityID     INT NOT NULL,
 stateID INT NOTNULL,
 cityName   varchar(50) NOT NULL,
 PRIMARY KEY (cityID),
 FOREIGN KEY (stateID) REFERENCES state (stateID));

First create an empty web application



Add model as per we did in earlier for entity framework do the necessary




Add a web page to the solution and copy paste this in .aspx page
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="cascading.aspx.cs" Inherits="counrtybasedropdown.cascading" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <center>
            <h3>
                Cascading DropDownList for Country/State/City in ASP.Net</h3>
            <table>
                <tr>
                    <td>
                        Select a Country :
                    </td>
                    <td>
                        <asp:DropDownList ID="ddlCountry" runat="server" AutoPostBack="true" OnSelectedIndexChanged="ddlCountry_SelectedIndexChanged">
                        </asp:DropDownList>
                    </td>
                </tr>
                <tr>
                    <td>
                        Select a State :
                    </td>
                    <td>
                        <asp:DropDownList ID="ddlState" runat="server" Enabled="false" AutoPostBack="true"
                            OnSelectedIndexChanged="ddlState_SelectedIndexChanged">
                        </asp:DropDownList>
                    </td>
                </tr>
                <tr>
                    <td>
                        Select a City :
                    </td>
                    <td>
                        <asp:DropDownList ID="ddlCity" runat="server" Enabled="false">
                        </asp:DropDownList>
                    </td>
                </tr>
            </table>
        </center>
    </div>
    </form>
</body>
</html>
Your .aspx.cs should be as follows
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace counrtybasedropdown
{
    public partial class cascading : System.Web.UI.Page
    {
        Database1Entities dbEntity = new Database1Entities();

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                var country = from c in dbEntity.countries select new { c.countryID, c.countryName };
                ddlCountry.DataSource = country.ToList();
                ddlCountry.DataValueField = "countryID";
                ddlCountry.DataTextField = "countryName";
                ddlCountry.DataBind();
                ddlCountry.Items.Insert(0, "--Select--");
            }
        }

        protected void ddlCountry_SelectedIndexChanged(object sender, EventArgs e)
        {
            int countyID = Convert.ToInt16(ddlCountry.SelectedValue.ToString());
            var state = from s in dbEntity.states where s.countryID.Equals(countyID) select new { s.stateID, s.stateName };
            ddlState.DataSource = state.ToList();
            ddlState.Enabled = true;
            ddlState.DataValueField = "stateID";
            ddlState.DataTextField = "stateName";
            ddlState.DataBind();
            ddlState.Items.Insert(0, "--Select--");
        }

        protected void ddlState_SelectedIndexChanged(object sender, EventArgs e)
        {
            int stateID = Convert.ToInt16(ddlState.SelectedValue.ToString());
            var city = from c in dbEntity.cities where c.stateID.Equals(stateID) select new { c.cityID, c.cityName };
            ddlCity.DataSource = city.ToList();
            ddlCity.Enabled = true;
            ddlCity.DataValueField = "cityID";
            ddlCity.DataTextField = "cityName";
            ddlCity.DataBind();
            ddlCity.Items.Insert(0, "--Select--");
        }
    }
}

Happy coding..
Feel free to ask queries...

Friday, December 21, 2012

Create dynamical Ajax Tab and filling data from database

I have attended an interview, there I asked a question like how to create a Tab container in asp.net dynamically with the department name from the database, and on selecting the particular Tab we would like to show the corresponding information of that department.

Here is a way to implement the task

First of all create 2 tables namely Employee and Department with a foreign key relation.

Employee table should contain the following columns ID(primary key), FirstName, LastName, DeptID(which is a foreign key)

Department table should contain the following columns DeptID(Primary key) and DepartmentName

Insert some data to the two tables as per our requirement, my sample data in the tables is as follows





Now as per our requirement I would like to show the department names on the Tabs. I used AJAX TabContainer 

Place a panel initially on the web form so that you design should be as follows


Your code should be like as follows
As I created an SqlDatabase file I have my connection string in web.config is as follows

<connectionStrings>
<add name="SqlCon" connectionString="data source=.\SQLEXPRESS;attachdbfilename=|DataDirectory|\NonPrimaryKeyTable.mdf;integrated security=True;user instance=True;" />
</connectionStrings>

You can change the connectionstring as per your requirement.



public partial class dynamicTab : System.Web.UI.Page
    {
        string strCon = ConfigurationManager.ConnectionStrings["SqlCon"].ConnectionString.ToString();
        TabContainer ajxTab;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                // createTab();
                
                SqlConnection con = new SqlConnection(strCon);
                SqlCommand cmd = new SqlCommand("select DeptID,DepartmentName from Department", con);
                con.Open();
                SqlDataAdapter da = new SqlDataAdapter();
                da.SelectCommand = cmd;
                DataSet ds = new DataSet();
                da.Fill(ds);
                for (int i = 0; i &lt; ds.Tables[0].Rows.Count; i++)
                {
                    Table tblDynamic = new Table();
                    TableRow tbrDynamic = new TableRow();
                    TableCell tbcDynamic = new TableCell();

                    GridView grdDyanmic = new GridView();
                    grdDyanmic.AutoGenerateColumns = true;

                    SqlCommand cmd1 = new SqlCommand("select * from Employee where DeptID='" + ds.Tables[0].Rows[i]["DeptID"].ToString() + "'", con);
                    SqlDataAdapter da1 = new SqlDataAdapter();
                    DataSet ds1 = new DataSet();
                    da1.SelectCommand = cmd1;
                    da1.Fill(ds1);
                   grdDyanmic.DataSource = ds1;
                    grdDyanmic.DataBind();
                    tbcDynamic.Controls.Add(grdDyanmic);
                    tbrDynamic.Cells.Add(tbcDynamic);
                    tblDynamic.Rows.Add(tbrDynamic);
                    ajxTab.Tabs[i].Controls.Add(tblDynamic);
                }
                pnlDynamic.Controls.Add(ajxTab);
            }
        }

        protected void page_init(object sender, EventArgs e)
        {
            createTab();

        }

        private void createTab()
        {
            SqlConnection con = new SqlConnection(strCon);
            SqlCommand cmd = new SqlCommand("select DeptID,DepartmentName from Department", con);
            con.Open();
            SqlDataAdapter da = new SqlDataAdapter();
            da.SelectCommand = cmd;
            DataSet ds = new DataSet();
            da.Fill(ds);
            ajxTab = new AjaxControlToolkit.TabContainer();
            for (int i = 0; i &lt; ds.Tables[0].Rows.Count; i++)
            {
                TabPanel tbpnlDynamic = new TabPanel();
                tbpnlDynamic.HeaderText = ds.Tables[0].Rows[i]["DepartmentName"].ToString();     
                tbpnlDynamic.ID = ds.Tables[0].Rows[i]["DeptID"].ToString();          // Here I am assigning DeptID to the TabPanel so that it will be easy to retrieve the data what we needed from database
                ajxTab.Tabs.Add(tbpnlDynamic);
                ajxTab.ActiveTabIndex = 0;
            }
        }
    }


Finally the output will be as follows



Hope you enjoyed the article, if any questions or queries please let me know.



Any comments welcome..



Popular Posts