Wednesday, April 16, 2014

"Order By" in Asp.NET

Open Visual Studio.

Create a Table.

Fill data in the table.

Then write following code in the Default.aspx ....


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!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>
   
        <asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True"
            onselectedindexchanged="DropDownList1_SelectedIndexChanged">
            <asp:ListItem>--Select--</asp:ListItem>
            <asp:ListItem>Ascending</asp:ListItem>
            <asp:ListItem>Descending</asp:ListItem>
        </asp:DropDownList>
        <br />
        <br />
        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
            BackColor="White" BorderColor="#999999" BorderStyle="Solid" BorderWidth="1px"
            CellPadding="3" ForeColor="Black" GridLines="Vertical">
            <AlternatingRowStyle BackColor="#CCCCCC" />
            <Columns>
                <asp:TemplateField HeaderText="ID">
                    <ItemTemplate>
                        <asp:Label ID="Label1" runat="server" Text='<%# bind("id") %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Name">
                    <ItemTemplate>
                        <asp:Label ID="Label2" runat="server" Text='<%# bind("name") %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Price">
                    <ItemTemplate>
                        <asp:Label ID="Label3" runat="server" Text='<%# bind("price") %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
            <FooterStyle BackColor="#CCCCCC" />
            <HeaderStyle BackColor="Black" Font-Bold="True" ForeColor="White" />
            <PagerStyle BackColor="#999999" ForeColor="Black" HorizontalAlign="Center" />
            <SelectedRowStyle BackColor="#000099" Font-Bold="True" ForeColor="White" />
            <SortedAscendingCellStyle BackColor="#F1F1F1" />
            <SortedAscendingHeaderStyle BackColor="#808080" />
            <SortedDescendingCellStyle BackColor="#CAC9C9" />
            <SortedDescendingHeaderStyle BackColor="#383838" />
        </asp:GridView>
   
    </div>
    </form>
</body>
</html>

Now in Default.aspx.cs :-


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;

public partial class _Default : System.Web.UI.Page
{
    SqlConnection cn;
    SqlDataAdapter da;

    protected void Page_Load(object sender, EventArgs e)
    {
        cn = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=E:\C#\WebSites\Order By\App_Data\Database.mdf;Integrated Security=True;User Instance=True");
    }

    protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (DropDownList1.SelectedItem.Text == "Ascending")
        {
            da = new SqlDataAdapter("Select* from Product order by Name ASC", cn);
            DataSet ds = new DataSet();
            da.Fill(ds);

            GridView1.DataSource = ds;
            GridView1.DataBind();
        }
        else
        {
            da = new SqlDataAdapter("Select* from Product order by Name DESC", cn);
            DataSet ds = new DataSet();
            da.Fill(ds);

            GridView1.DataSource = ds;
            GridView1.DataBind();
        }
    }
}

Output :-



Tuesday, April 15, 2014

Export GridView to Excel Asp.NET

"File" - "New WebSite" - "Empty WebSite"
Then right-click on the Solution Explorer and select "Add New Item" - "Default.aspx" page.
Then add one button, one label and a GridView to the page.

Create a table in sql server :-



Default.aspx:-


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!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>
   
        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
            BackColor="White" BorderColor="#CC9966" BorderStyle="None" BorderWidth="1px"
            CellPadding="4">
            <Columns>
                <asp:TemplateField HeaderText="ID">
                    <ItemTemplate>
                        <asp:Label ID="Label1" runat="server" Text='<%# bind("ID") %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Name">
                    <ItemTemplate>
                        <asp:Label ID="Label2" runat="server" Text='<%# bind("Name") %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="City">
                    <ItemTemplate>
                        <asp:Label ID="Label3" runat="server" Text='<%# bind("City") %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
            <FooterStyle BackColor="#FFFFCC" ForeColor="#330099" />
            <HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="#FFFFCC" />
            <PagerStyle BackColor="#FFFFCC" ForeColor="#330099" HorizontalAlign="Center" />
            <RowStyle BackColor="White" ForeColor="#330099" />
            <SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="#663399" />
            <SortedAscendingCellStyle BackColor="#FEFCEB" />
            <SortedAscendingHeaderStyle BackColor="#AF0101" />
            <SortedDescendingCellStyle BackColor="#F6F0C0" />
            <SortedDescendingHeaderStyle BackColor="#7E0000" />
        </asp:GridView>
   
        <br />
        <br />
        <asp:Button ID="Button1" runat="server" onclick="Button1_Click"
            Text="Download as Excel" />
   
    </div>
    </form>
</body>
</html>

Default.aspx.cs :-


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.IO;

public partial class _Default : System.Web.UI.Page
{
    SqlConnection cn;
    SqlDataAdapter da;

    protected void Page_Load(object sender, EventArgs e)
    {
        cn = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=E:\C#\WebSites\Export To Excel GridView\App_Data\Database.mdf;Integrated Security=True;User Instance=True");

        mahi();
    }

    protected void mahi()
    {
        da = new SqlDataAdapter("Select* from Details", cn);

        DataSet ds = new DataSet();
        da.Fill(ds);

        GridView1.DataSource = ds;
        GridView1.DataBind();
    }

    public override void VerifyRenderingInServerForm(Control control)
    {
        //required to avoid the run time error "  
        //Control 'GridView1' of type 'Grid View' must be placed inside a form tag with runat=server."  
    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        Response.Clear();
        Response.Buffer = true;
        Response.ClearContent();
        Response.ClearHeaders();
        Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", "MyFriends.xls"));
        Response.ContentType = "application/ms-excel";

        GridView1.HeaderStyle.Font.Bold = true;
        GridView1.HeaderRow.Style.Add("background-color", "#FFFFFF");
        GridView1.GridLines = GridLines.Both;


        StringWriter sw = new StringWriter();
        HtmlTextWriter hw = new HtmlTextWriter(sw);
        GridView1.AllowPaging = false;
        mahi();
        GridView1.RenderControl(hw);
        Response.Write(sw.ToString());
        Response.End();
    }
}

Wednesday, April 9, 2014

Simple Registration and Login form in Asp.NET

First create a table that contains 5 columns (ID, first_name,last_name,Email,Password)


Then add form and name it as StartPage.aspx and write down the following code


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="StartPage.aspx.cs" Inherits="StartPage" %>

<!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">
   
    <center style="font-family: 'Berlin Sans FB Demi'; font-size: xx-large; color: #FF0000">Welcome To ABC.com</center><br />
    <br />
    <br />
   
    <asp:Label ID="Label1" runat="server" Text="New User? Sign Up here"></asp:Label>
    &nbsp;
    <asp:Button ID="Button1" runat="server" ForeColor="#FF0066"
        onclick="Button1_Click" Text="SignUp" />
    <br />
    <br />
    <asp:Label ID="Label2" runat="server" Text="Already have an account?"></asp:Label>
&nbsp;&nbsp;
    <asp:Button ID="Button2" runat="server" ForeColor="#FF0066"
        onclick="Button2_Click" Text="LogIn" />
    </form>
</body>
</html>

and write the following code in StartPage.aspx.cs


protected void Button1_Click(object sender, EventArgs e)
    {
        Response.Redirect("Default.aspx");
    }
    protected void Button2_Click(object sender, EventArgs e)
    {
        Response.Redirect("LogIn.aspx");
    }

Now create another form and name it as SignUp.aspx and write the following code in it


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!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>
    <style type="text/css">
        .style1
        {
            width: 107px;
        }
    </style>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    
        <table style="width:27%;" align="center">
            <tr>
                <td class="style1">
                    First Name</td>
                <td>
                    <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
                </td>
                
            </tr>
            <tr>
                <td class="style1">
                    Last Name</td>
                <td>
                    <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td class="style1">
                    Email</td>
                <td>
                    <asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>
                </td>
            </tr>
            </tr>
            <tr>
                <td class="style1">
                    Password</td>
                <td>
                    <asp:TextBox ID="TextBox4" runat="server" TextMode="Password"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td class="style1">
                    &nbsp;</td>
                <td>
                    <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="SignUp" 
                        ForeColor="#FF0066" />
                </td>
            </tr>
        </table>
    
    </div>
    </form>
</body>
</html>

now write the following code in SignUp.aspx.cs :-


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;

public partial class _Default : System.Web.UI.Page
{
    SqlConnection cn;
    SqlCommand cmd;
    SqlDataAdapter da;

    protected void Page_Load(object sender, EventArgs e)
    {
        cn = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=E:\C#\WebSites\Registration1\App_Data\Database.mdf;Integrated Security=True;User Instance=True");
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        cmd = new SqlCommand("Insert into SignUp values(@first_name,@last_name,@Email,@Password)", cn);

        cmd.Parameters.AddWithValue("@first_name", TextBox1.Text);
        cmd.Parameters.AddWithValue("@last_name", TextBox2.Text);
        cmd.Parameters.AddWithValue("@Email", TextBox3.Text);
        cmd.Parameters.AddWithValue("@Password", TextBox4.Text);

        cn.Open();
        cmd.ExecuteNonQuery();
        cn.Close();
    }
}

Again add another web form and save it as LogIn.aspx. write there:-


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="LogIn.aspx.cs" Inherits="LogIn" %>

<!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>
    <style type="text/css">
        .style1
        {
            height: 23px;
        }
        .style2
        {
            height: 23px;
            width: 101px;
        }
        .style3
        {
            width: 101px;
        }
        .style4
        {
            height: 23px;
            width: 130px;
        }
        .style5
        {
            width: 130px;
        }
    </style>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    
        <table align="center" style="width:50%;">
            <tr>
                <td class="style2">
                    Email</td>
                <td class="style4">
                    <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
                    <asp:RequiredFieldValidator ID="rfvUser" ErrorMessage="Please enter Email ID" ControlToValidate="TextBox1" runat="server" />
                </td>
            <tr>
                <td class="style3">
                    Password </td>
                <td class="style5">
                    <asp:TextBox ID="TextBox2" runat="server" TextMode="Password"></asp:TextBox>
                    <asp:RequiredFieldValidator ID="rfvPWD" runat="server" ControlToValidate="TextBox2" ErrorMessage="Please enter Password"/>
                </td>
            </tr>
            <tr>
                <td class="style3">
                    &nbsp;</td>
                <td class="style5">
                    <asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />
                </td>
            </tr>
        </table>
    
    </div>
    <br />
    <br />
    <br />
    <asp:Label ID="Label1" runat="server"></asp:Label>
    </form>
</body>
</html>

Now add following code in LogIn.aspx.cs


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;

public partial class LogIn : System.Web.UI.Page
{
    SqlConnection cn;
    SqlCommand cmd;
    SqlDataAdapter da;

    protected void Page_Load(object sender, EventArgs e)
    {
        cn = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=E:\C#\WebSites\Registration1\App_Data\Database.mdf;Integrated Security=True;User Instance=True");
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        da = new SqlDataAdapter("Select * from SignUp where Email=@Email and Password=@Password", cn);

        da.SelectCommand.Parameters.AddWithValue("@Email", TextBox1.Text);
        da.SelectCommand.Parameters.AddWithValue("@Password", TextBox2.Text);

        DataSet ds = new DataSet();
        da.Fill(ds);

        if (ds.Tables[0].Rows.Count != 0)
            Response.Redirect("Home.aspx");

        else
            Label1.Text = "Incorrect Email and Password";
    }
}

At last add another form and save it as HomePage.aspx :-


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %>

<!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>
    This is your home page....
    </div>
    </form>
</body>
</html>

Finish




Monday, April 7, 2014

Simple way to fetch data from database into dropdownlist Asp.NET

First Create a Table 


Then Save it.
Then add data into table


Drag dropdownlist control from toolbox in default.aspx file :-


<asp:DropDownList ID="DropDownList1" runat="server">
        </asp:DropDownList>

Now write the following code in Default.aspx.cs


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;

public partial class _Default : System.Web.UI.Page
{
    SqlConnection cn;
    SqlCommand cmd;
    SqlDataAdapter da;

    protected void Page_Load(object sender, EventArgs e)
    {
        cn = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=E:\C#\WebSites\DropDownList DataBase 4\App_Data\Database.mdf;Integrated Security=True;User Instance=True");

        cmd = new SqlCommand("Select * from Mahi", cn);

        da = new SqlDataAdapter(cmd);

        DataSet ds = new DataSet();
        da.Fill(ds);

        DropDownList1.DataSource = ds;
        DropDownList1.DataTextField = "Name";
        DropDownList1.DataValueField = "ID";
        DropDownList1.DataBind();
    }
}

Fetch data from database and insert it into DropDownList Asp.NET Part-3

First Create a Table in database as below :

Then save it.
Then add details in the table :-

Add form n write the following code :- Default.aspx :-


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!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>
        <asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True">
        </asp:DropDownList>
        &nbsp;
        <asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click1" Style="height: 26px" />
        <br />
        <br />
        <br />
        <asp:GridView ID="GridView1" runat="server" BackColor="White" BorderColor="#999999"
            BorderStyle="Solid" BorderWidth="1px" CellPadding="3" GridLines="Vertical"
            ForeColor="Black">
            <AlternatingRowStyle BackColor="#CCCCCC" />
            <FooterStyle BackColor="#CCCCCC" />
            <HeaderStyle BackColor="Black" Font-Bold="True" ForeColor="White" />
            <PagerStyle BackColor="#999999" ForeColor="Black" HorizontalAlign="Center" />
            <SelectedRowStyle BackColor="#000099" Font-Bold="True" ForeColor="White" />
            <SortedAscendingCellStyle BackColor="#F1F1F1" />
            <SortedAscendingHeaderStyle BackColor="#808080" />
            <SortedDescendingCellStyle BackColor="#CAC9C9" />
            <SortedDescendingHeaderStyle BackColor="#383838" />
        </asp:GridView>
    </div>
    </form>
</body>
</html>

Then write the following code in the Default.aspx.cs :-


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;

public partial class _Default : System.Web.UI.Page
{
    SqlConnection cn;
    SqlDataAdapter da;

    protected void Page_Load(object sender, EventArgs e)
    {
        cn = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=E:\C#\WebSites\DropDownList DataBase 3\App_Data\Database.mdf;Integrated Security=True;User Instance=True");
        if (!IsPostBack)
        {
            mahi();
        }
    }

    protected void mahi()
    {
        da = new SqlDataAdapter("Select* from Mahi",cn);
        DataSet ds = new DataSet();
        da.Fill(ds);
        DropDownList1.DataSource = ds;
        DropDownList1.DataTextField = "Name";
        DropDownList1.DataValueField = "ID";
        DropDownList1.DataBind();
    }
    protected void Button1_Click1(object sender, EventArgs e)
    {
        da = new SqlDataAdapter("select * from Mahi where id = '" + DropDownList1.SelectedValue + "'", cn);
        DataSet ds = new DataSet();
        da.Fill(ds);
        GridView1.DataSource = ds;
        GridView1.DataBind();
    }
}

Output :-




Fetch data from database and insert it into DropDownList Asp.NET Part-2

First we need to create 3 Tables in SQL Server Database.


1) Country Table :

2) State Table :

3) Region Table :

Now fill data in the tables as follows :-


1) Country Table :

2) State Table :

3) Region Table :

Your Default.aspx page :-


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!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>
    <style type="text/css">
        .style1
        {
            width: 93px;
        }
        .style2
        {
            width: 93px;
            height: 26px;
        }
        .style3
        {
            height: 26px;
            width: 96px;
        }
        .style4
        {
            width: 96px;
        }
    </style>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <table align="center">
        <tr>
            <td>
                Country:
            </td>
            <td>
                <asp:DropDownList ID="ddlCountry" runat="server" AutoPostBack="true"
                    onselectedindexchanged="ddlCountry_SelectedIndexChanged"></asp:DropDownList>
            </td>
        </tr>
        <tr>
            <td>
                State:
            </td>
            <td>
                <asp:DropDownList ID="ddlState" runat="server" AutoPostBack="true"
                    onselectedindexchanged="ddlState_SelectedIndexChanged"></asp:DropDownList>
            </td>
        </tr>
        <tr>
            <td>
                Region:
            </td>
            <td>
                <asp:DropDownList ID="ddlRegion" runat="server"></asp:DropDownList>
            </td>
        </tr>
    </table>
    </div>
    </form>
</body>
</html>

Your Default.aspx.cs Page :-


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;

public partial class _Default : System.Web.UI.Page
{
    SqlConnection cn;
    protected void Page_Load(object sender, EventArgs e)
    {
        cn = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=E:\C#\WebSites\DropDownList DataBase 2\App_Data\Database.mdf;Integrated Security=True;User Instance=True");
        if (!IsPostBack)
        {
            BindContrydropdown();
        }
    }

    protected void BindContrydropdown()
    {
        //conenction path for database
        cn.Open();
        SqlCommand cmd = new SqlCommand("select * from Country", cn);
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        DataSet ds = new DataSet();
        da.Fill(ds);
        cn.Close();
        ddlCountry.DataSource = ds;
        ddlCountry.DataTextField = "Cname";
        ddlCountry.DataValueField = "Cid";
        ddlCountry.DataBind();
        ddlCountry.Items.Insert(0, new ListItem("--Select--", "0"));
        ddlState.Items.Insert(0, new ListItem("--Select--", "0"));
        ddlRegion.Items.Insert(0, new ListItem("--Select--", "0"));

    }

    protected void ddlCountry_SelectedIndexChanged(object sender, EventArgs e)
    {
        int CountryID = Convert.ToInt32(ddlCountry.SelectedValue);
        cn.Open();
        SqlCommand cmd = new SqlCommand("select * from State where Cid=" + CountryID, cn);
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        DataSet ds = new DataSet();
        da.Fill(ds);
        cn.Close();
        ddlState.DataSource = ds;
        ddlState.DataTextField = "Sname";
        ddlState.DataValueField = "Sid";
        ddlState.DataBind();
        ddlState.Items.Insert(0, new ListItem("--Select--", "0"));
        if (ddlState.SelectedValue == "0")
        {
            ddlRegion.Items.Clear();
            ddlRegion.Items.Insert(0, new ListItem("--Select--", "0"));
        }

    }

    protected void ddlState_SelectedIndexChanged(object sender, EventArgs e)
    {
        int StateID = Convert.ToInt32(ddlState.SelectedValue);
        cn.Open();
        SqlCommand cmd = new SqlCommand("select * from Region where Sid=" + StateID, cn);
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        DataSet ds = new DataSet();
        da.Fill(ds);
        cn.Close();
        ddlRegion.DataSource = ds;
        ddlRegion.DataTextField = "Name";
        ddlRegion.DataValueField = "Rid";
        ddlRegion.DataBind();
        ddlRegion.Items.Insert(0, new ListItem("--Select--", "0"));
    }
}

Output:-





Fetch data from database and insert it into DropDownList using 3 tier structure Asp.NET Part-1

Create a from in Visual Studio Default.aspx :-


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!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>Fetch items from database in DropDownList</title>
    <style type="text/css">
        .style1
        {
            width: 93px;
        }
        .style2
        {
            width: 93px;
            height: 26px;
        }
        .style3
        {
            height: 26px;
            width: 96px;
        }
        .style4
        {
            width: 96px;
        }
    </style>
</head>
<body>
    <form id="form1" runat="server">
    <div>
 
        <table style="width:22%;" align="center">
            <tr>
                <td class="style2">
                    Country :</td>
                <td class="style3">
                    <asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True"
                        onselectedindexchanged="DropDownList1_SelectedIndexChanged">
                    </asp:DropDownList>
                </td>
            </tr>
            <tr>
                <td class="style1">
                    State :</td>
                <td class="style4">
                    <asp:DropDownList ID="DropDownList2" runat="server" AutoPostBack="True">
                    </asp:DropDownList>
                </td>
            </tr>
        </table>
 
    </div>
    </form>
</body>
</html>

Create Two Table in DataBase as follows :-


1) Country :-


2) State :-



Add details in the table whatever you want to add.

Now add two class :-


1) DataLayer.cs :-


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.SqlClient;

/// <summary>
/// Summary description for DataLayer
/// </summary>
public class DataLayer
{
    SqlConnection cn;
    SqlCommand cmd;
    SqlDataAdapter da;

public DataLayer()
{
        cn = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=E:\C#\WebSites\DropDownList DataBase 1\App_Data\Database.mdf;Integrated Security=True;User Instance=True");
}

    public DataSet get_country()
    {
        da = new SqlDataAdapter("Select* from Country", cn);
        DataSet ds = new DataSet();
        da.Fill(ds);
        return ds;
    }

    public DataSet get_state(LogicLayer li)
    {
        da = new SqlDataAdapter("Select* from State where c_id=@id", cn);
        da.SelectCommand.Parameters.AddWithValue("@id", li.country_id);

        DataSet ds = new DataSet();
        da.Fill(ds);
        return ds;
    }
}

2) LogicLayer.cs


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

/// <summary>
/// Summary description for LogicLayer
/// </summary>
public class LogicLayer
{
    public string country_id { get; set; }
public LogicLayer()
{
//
// TODO: Add constructor logic here
//
}
}

Now add following code in the Default.aspx.cs :-


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page
{
    LogicLayer li = new LogicLayer();
    DataLayer dl = new DataLayer();

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            DropDownList1.DataSource = dl.get_country();
            DropDownList1.DataTextField = "c_name";
            DropDownList1.DataValueField = "c_id";
            DropDownList1.DataBind();
            DropDownList1.Items.Insert(0, "---Select---");
        }
    }
    protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
    {
        li.country_id = DropDownList1.SelectedValue;

        DropDownList2.DataSource = dl.get_state(li);
        DropDownList2.DataTextField = "s_name";
        DropDownList2.DataValueField = "s_id";
        DropDownList2.DataBind();
    }
}

Output :-


1) 

2)