-->

Tuesday, February 6, 2018

Step By Step Guide to use WebAPI in ASP.NET CORE WebApplication

If you have to completed your WebAPI then must to know , how to use it in web application.  Now , you can see , how to use WebAPI in WebApplication.

WEBAPI Project
Step-1 :   Create Model first
public class Student
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }

Step-2 :  Create Data Context Class

public class Context : DbContext
    {
        public Context(DbContextOptions<Context> options) : base(options)
        {

        }
        public DbSet<Student> Students { get; set; }

    }

Step-3 :  Add Connection String into your Application Setting File

{
  "ConnectionStrings": {
    "DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=aspnet-WebApplication1-6550C064-027F-4939-822B-5B4620D08657;Trusted_Connection=True;MultipleActiveResultSets=true"
  },
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Warning"
    }
  }
}

Step-4 :  Add Connection String in Startup file

  services.AddDbContext<ApplicationDbContext>(options =>
                options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));


Step-5 Do Migration 
Step-6 :  Create Controller 

namespace WebApiTestApplication.Controllers
{
    [Route("api/[controller]")]
    public class StudentController : Controller
    {
        private Context _context;
        public StudentController(Context context)
        {
            _context = context;
        }
        [HttpGet]
        public List<Student> Get()
        {
            return _context.Students.ToList();
        }

        public IActionResult Index()
        {
            return View();
        }
    }}

Step- 7: Add new project Web Application in the same solution
Step-8 : Add Helper Class  also add View Model class

namespace WebApplication1.Helper
{
    public class StudentAPI
    {
        public HttpClient Initial()
        {
            var Client = new HttpClient();
            Client.BaseAddress = new Uri("http://localhost:56562/");
            return Client;
        }
    }

}

If you Know what is "56562" then must to watch the video

And the model class

namespace WebApiTestApplication.Models
{
    public class Student
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }
}

Step-9 :  Add A controller

namespace WebApplication1.Controllers
{
    public class HomeController : Controller
    {
        StudentAPI _api = new StudentAPI();

        public async Task<IActionResult> Index()
        {
            List<Student> student = new List<Student>();
            HttpClient client = _api.Initial();
            HttpResponseMessage res = await client.GetAsync("api/Student");
            if (res.IsSuccessStatusCode)
            {
                var result = res.Content.ReadAsStringAsync().Result;
                student = JsonConvert.DeserializeObject<List<Student>>(result);
            }
         
            return View(student);
        }


    }
}

Step-10  : Generate View as list type 

@model IEnumerable<WebApiTestApplication.Models.Student>

@{
    ViewData["Title"] = "Index";
}

<h2>Index</h2>

<p>
    <a asp-action="Create">Create New</a>
</p>
<table class="table">
    <thead>
        <tr>
                <th>
                    @Html.DisplayNameFor(model => model.Id)
                </th>
                <th>
                    @Html.DisplayNameFor(model => model.Name)
                </th>
            <th></th>
        </tr>
    </thead>
    <tbody>
@foreach (var item in Model) {
        <tr>
            <td>
                @Html.DisplayFor(modelItem => item.Id)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Name)
            </td>
            <td>
                @Html.ActionLink("Edit", "Edit", new { /* id=item.PrimaryKey */ }) |
                @Html.ActionLink("Details", "Details", new { /* id=item.PrimaryKey */ }) |
                @Html.ActionLink("Delete", "Delete", new { /* id=item.PrimaryKey */ })
            </td>
        </tr>
}
    </tbody>
</table>



Wednesday, June 15, 2016

How to use FileUpload Control in ASP.NET

Introduction
The FileUpload control displays a text box control and a browse button that enable users to browse a file from the local or remote machine to upload it on the Web server. You can upload a file on the Web Server by specifying the full path of the file to be uploaded (for example D:\Myfiles\Test.txt) in the textbox of this control . Alternatively , you can select the file by clicking the browse button , and then locating it in the Choose File dialog box.

Top Related article


  1. Fileupload control enable disable programmatically in ASP.NET
  2. Programmatically change border color of fileupload control in ASP.NET
  3. Programmatically change background color of fileupload control in ASP.NET
  4. How to validate fileupload control in asp.net also choose selected format
  5. How to insert image into database using file upload control


Public Properties of the FileUpload Class
FileBytes : Obtains an array of the bytes in a file that is specified by using a FileUpload control

FileContent : Obtains a Stream object that points to a file to upload using the FileUpload control.

FileName : Obtains the name of a file on a client to upload using the FileUpload control.

HasFile : Obtains a value indicating whether the FileUpload control contains a file.

PostedFile : Obtains the underlying HttpPostedFile object for a file that is uploaded by using the FileUpload control.

Public Method of the FileUpload Class
SaveAs : Saves the data of an uploaded file to a specified path on the web server.

Example of FileUpload control in ASP.NET

<%@ Page Language="C#" %>
<!DOCTYPE html>
<script runat="server">
    protected void Button1_Click(object sender, EventArgs e)
    {
        if (FileUpload1.HasFile)
        {
            FileUpload1.SaveAs(Server.MapPath("~/images/" + FileUpload1.FileName));
        }
        else
        {
            emptyupload.Text = "Choose your file"; 
        }
    }
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <style type="text/css">
        .auto-style1 {
            font-size: larger;
        }
    </style>
</head>
<body>
    <form id="form1" runat="server">
    <div class="auto-style1">
   
        <strong>Pick Your file from file upload control<br />
        </strong>
        <asp:FileUpload ID="FileUpload1" runat="server" />
        <br />
        <br />
        <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Save" />   
        <br />
        <asp:Label ID="emptyupload" runat="server"></asp:Label>   
    </div>
    </form>
</body>
</html>
Output
Example of file upload control in asp.net

Example of file upload control

Only GIF image support by FileUpload control   


<script runat="server">
    protected void Button1_Click(object sender, EventArgs e)
    {        string extn=string.Empty ;
        if (FileUpload1.HasFile)
        {
            extn = System.IO.Path.GetExtension(FileUpload1.FileName);
            if ("gif" == extn)
            {
                FileUpload1.SaveAs(Server.MapPath("~/images/" + FileUpload1.FileName));
                emptyupload.Text = "Save sucessfully";
            }
            else
            {
                emptyupload.Text = "only gif support";
            }
        }
        else
        {
            emptyupload.Text = "Choose your file"; 
        }
    }
</script>
Note : GetExtension is the method of the path class which is detect extension of the filename.

Multiple File Upload control on Same Page

This is the new features comes into the DOTNET Framework 3.5. If you have three or more file upload control on same page then what to do for save files into project directory. If you use traditional code like
if(fileupload1.hasfile)
{
//code)}
if(fileupload2.hasfile)
{
//code
}
This is the wrong for developer perspective. You can use new features of DOTNET Framework 3.5 i.e HttpFileCollection class.  By using Request.Files property you can get the files from the server.
Check the simple example of it.


Source Code:

 <div>
 
        <asp:FileUpload ID="FileUpload1" runat="server" />
        <br />
        <asp:FileUpload ID="FileUpload2" runat="server" />
        <br />
        <asp:FileUpload ID="FileUpload3" runat="server" />
        <br />
        <br />
        <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Submit" />
        <br />
        <asp:Label ID="Label1" runat="server"></asp:Label>
 
    </div>
  protected void Button1_Click(object sender, EventArgs e)
    {
        string filepath = "E:\\Upload";
        HttpFileCollection hfc = Request.Files;
        for (int i = 0; i < hfc.Count; i++)
        {
            HttpPostedFile hpf = hfc[i];
            try
            {
                if (hpf.ContentLength>0)
                {
                    Label1.Text += "File Content Type: " + hpf.ContentType+"<br/>";
                    Label1.Text += "File Size: " + hpf.ContentLength + "<br/>";
                    Label1.Text += "File Name: " + hpf.FileName + "<br/>";
                    hpf.SaveAs(filepath + "\\" + System.IO.Path.GetFileName(hpf.FileName));
                    Label1.Text += "Location of the file: " + filepath + "\\" + System.IO.Path.GetFileName(hpf.FileName);
                 
                }
            }
            catch (Exception ex)
            {

                Label1.Text += "Error: " + ex.Message;
            }
        }

    }
Code Generate the following output:

Multiple File Upload control on Same Page

Monday, June 13, 2016

ASP.NET Searching Data using SqlDataSource Control

In this article, i will show you, How to search data from database table using SqlDataSource control. Visual Studio SqlDataSource control have inbuilt many functionality to make dynamic application. By using SqlDataSource control you can do different types of functionality like Sorting, Searching, Insert, Update, Delete data. In this article i will show you an example of searching/filtering data from database table. So first of Design a Database table using Sql Server Explorer. Now, you can take  three tuples in it. I have a Database table schema, you can check.

Search Data From Database table using SqlDataSource Control:

1. First to add one TextBox, One Button and a GridView control in a page.
2. By using Show Smart tag you can configure your GridView Control with the database table using SqlDataSource control.
3. When you configure your SqlDataSource control please check the Where clause button. In it you can select Field name, which is used to searching. Operator is "=" and parameter is control.  
4. You can Run your Web Site.

The Complete Source Code:

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

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
   
        Enter Name:
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
        <br />
   
    </div>
        <asp:Button ID="Button1" runat="server" Text="Search Student Details" />
        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="StudentId" DataSourceID="SqlDataSource1">
            <Columns>
                <asp:BoundField DataField="StudentId" HeaderText="StudentId" InsertVisible="False" ReadOnly="True" SortExpression="StudentId" />
                <asp:BoundField DataField="StudentName" HeaderText="StudentName" SortExpression="StudentName" />
                <asp:BoundField DataField="StudentCity" HeaderText="StudentCity" SortExpression="StudentCity" />
            </Columns>
        </asp:GridView>

        <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>" SelectCommand="SELECT * FROM [Student] WHERE ([StudentName] = @StudentName)">
            <SelectParameters>
                <asp:ControlParameter ControlID="TextBox1" Name="StudentName" PropertyName="Text" Type="String" />
            </SelectParameters>
        </asp:SqlDataSource>

    </form>
</body>
</html>

Code Generate the Following output:

ASP.NET Searching Data using SqlDataSource Control

Tuesday, May 24, 2016

Import Export project in ASP.NET C#

Project Introduction:

In this project, we have some modules, which is related to Import and Export goods services. This project provides online facilities to pickup your goods from any where in the nation. Actually projects is based on packers and movers functionality. Lots of goods transport one place to another place. We all know about import and export. Suppose, you want to bring goods from other places and that place is far from you place. So , you face too much difficulties. So, i design a packer and mover based project in ASP.NET C#.

Project modules

Project contains lots of things which is related to customer as well as company who pick up goods. So i dived the project in different categories, categories further divided in sub categories.
Module:
  1. User Module (Who Generate pick up request)
  2. Branch Module(Who handle pick up request , i am taking state level branch module)
  3. Agent Module (Who deliever the goods)
  4. Admin (Who handle all such functionality)

Software Requirement of the project : Visual Studio 2013

Front-End and Back End of the project : 

Front-End  : ASP.NET C# ( Here c# work as business logic code)
Back-End : Sql Server 

Project Video :



How to Download the Project:

Mail Me  : narenkumar851@gmail.com 

Sunday, May 22, 2016

How to use ImageMap Control in ASP.NET

Introduction

An image map is a picture on a webpage that provides various links , called hotspots, to navigate to other web pages , depending on the place where the user click (on single image). Web Designer frequently use image maps in their websites . An image map can be included in your web page by using the ImageMap Control.

An ImageMap control exists within the System.Web.UI.WebControls namespace. Image maps are often real maps; for example , you can display the map of the USA and define hotspot regions for each of its state and then navigate to the corresponding page containing the information for the selected state.


Public Properties of the ImageMap Class
Enable : Obtains or sets a value indicating whether the control can respond to user interaction.

HotSpotMode : Obtains or sets the default behavior for the HotSpot objects of an ImageMap control when the HotSpot objects are clicked.

HotSpots : Obtains or sets a group of HotSpot objects that represents the defined hotspot regions in an ImageMap Control.

Target : Obtains or sets the target window to show the Web page content when the ImageMap control is clicked.

Public Event of the ImageMap Class
Click : Occurs when a HotSpot object in an ImageMap control is clicked.
<%@ Page Language="C#" %>
<!DOCTYPE html>
<script runat="server">
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
            <asp:ImageMap ID="ImageMap1" runat="server" Height="227px" HotSpotMode="Navigate" ImageUrl="~/imagemap.jpg" Width="227px">
            <asp:RectangleHotSpot HotSpotMode="Navigate" Left="10" NavigateUrl="http://www.google.com" Top="100" />
            <asp:RectangleHotSpot HotSpotMode="Navigate" Left="3" NavigateUrl="http://www.microsoft.com" Top="200" />
        </asp:ImageMap>
   
    </div>
    </form>
</body>
</html>
Output
hotspot

Saturday, May 21, 2016

How to Bind Hyperlink control in datalist in asp.net

Datalist introduction
The Datalist control is a data bound control that displays data by using templates. These templates define controls and HTML elements that should be displayed for an item. The Datalist control exists within the System.Web.UI.WebControl namespace.

Related topics



Some steps for binding Hyperlink control in Datalist

Step-1: Create a DataBase Table with  following fields.


Step-2: Fill this field with following values 

DepartmentID           Name                 Description
1                                  IT                     This is first department Name
2                                  CS                    This is Second Department Name


Step-3 : Create Procedure for retrieving values.

Database.mdf-->Stored Procedures -->Right click -->Add new Stored Procedure

CREATE PROCEDURE GetDepartments
AS
SELECT DepartmentID ,Name ,Description From [Table] ;

RETURN 0

Step-4: Take  a webform in your project name as "Departmentlist.aspx"
Step-5:  Paste this code into your Department.aspx





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

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <asp:DataList ID="DataList1" runat="server">
            <HeaderTemplate>
                Choose a Department
            </HeaderTemplate>
            <ItemTemplate>
                <asp:HyperLink ID="HyperLink1" runat="server" NavigateUrl ='<%#Link .ToDepartment (Eval ("DepartmentID").ToString ()) %>'
                  Text ='<%# HttpUtility .HtmlEncode (Eval ("Name").ToString ()) %>' ToolTip ='<%# HttpUtility .HtmlEncode (Eval ("Description").ToString ()) %>'   >

                </asp:HyperLink>
            </ItemTemplate>
        </asp:DataList>
    <div>
    
    </div>
    </form>
</body>
</html>

Step-6: Paste this code into your codebehind file


using System;
using System.Data.SqlClient;
using System.Data;


public partial class Departmentlist : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        SqlConnection con = new SqlConnection();
        con.ConnectionString = @"Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True";
            con.Open ();
        SqlCommand cmd=new SqlCommand ();
        cmd.CommandText ="GetDepartments";
        cmd.CommandType =CommandType .StoredProcedure ;
        cmd.Connection =con;
        DataSet ds = new DataSet();
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        da.Fill(ds, "Department");
        DataList1.DataSource = ds;
        DataList1.DataBind();



    }
}

Step-7 Make a Link class for absolute url


using System;
using System.Web;

/// <summary>
/// Summary description for Link
/// </summary>
public class Link
{
    public static string BuildAbsolute(string relativeuri)
    {
        // get current uri
        Uri uri = HttpContext.Current.Request.Url;
        // build absolute path
        string app = HttpContext.Current.Request.ApplicationPath;
        if (!app.EndsWith("/"))
               
            app += "/";
        relativeuri = relativeuri.TrimStart('/');
        // return the absolute path
        return HttpUtility .UrlPathEncode (String .Format ("http://{0}:{1}{2}",uri .Host ,uri.Port ,app ));

 

    }
    public static string ToDepartment(string departmentId, string page)
    {
        if (page == "1")
     
            return BuildAbsolute(string.Format("catalog.aspx?DepartmentID={0}", departmentId));
        else
            return BuildAbsolute (string .Format ("catalog.aspx?DepartmentID={0}&Page={1}",departmentId,page ));
           

    }
    //generate a department url for the first page
    public static string ToDepartment(string departmentId)
    {
        return ToDepartment(departmentId, "1");
    }

 
}


Out Put 

Friday, May 20, 2016

Pager Template in FormView Example of ASP.NET C#

In this article i will show you, How to customize paging of FormView using pager template. By using pager template we can changed the structure of paging. I will give you an example of pager template. In this example i will show you, How to prepare paging structure in FormView, after preparing the structure of Edit Item template and Item Template , you can put the structure of pager template. In this example, pager template contain two link button with CommandName and CommandArgument. In CommandName we have single value for both control i.e Page, But CommandArgument contain value i.e "Prev" and "Next". Both CommandArguments are used for specific purpose. I will show you DataBound event, In this, we have pager template information.



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

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    
    </div>
        <asp:FormView  ID="FormView1" runat="server" DataKeyNames="Id" AllowPaging="True" OnDataBound="FormView1_DataBound" OnPageIndexChanging="FormView1_PageIndexChanging">
            <EditItemTemplate>
                Id:
                <asp:Label ID="IdLabel1" runat="server" Text='<%# Eval("Id") %>' />
                <br />
                Name:
                <asp:TextBox ID="NameTextBox" runat="server" Text='<%# Bind("Name") %>' />
                <br />
                <asp:LinkButton ID="UpdateButton" runat="server" CausesValidation="True" CommandName="Update" Text="Update" />
                &nbsp;<asp:LinkButton ID="UpdateCancelButton" runat="server" CausesValidation="False" CommandName="Cancel" Text="Cancel" />
            </EditItemTemplate>
            <InsertItemTemplate>
                Id:
                <asp:TextBox ID="IdTextBox" runat="server" Text='<%# Bind("Id") %>' />
                <br />
                Name:
                <asp:TextBox ID="NameTextBox" runat="server" Text='<%# Bind("Name") %>' />
                <br />
                <asp:LinkButton ID="InsertButton" runat="server" CausesValidation="True" CommandName="Insert" Text="Insert" />
                &nbsp;<asp:LinkButton ID="InsertCancelButton" runat="server" CausesValidation="False" CommandName="Cancel" Text="Cancel" />
            </InsertItemTemplate>
            <ItemTemplate>
                Id:
                <asp:Label ID="IdLabel" runat="server" Text='<%# Eval("Id") %>' />
                <br />
                Name:
                <asp:Label ID="NameLabel" runat="server" Text='<%# Bind("Name") %>' />
                <br />

                <asp:LinkButton ID="LinkButton3" runat="server" CommandName="Edit">Edit</asp:LinkButton>
                <br />

            </ItemTemplate>
             
            <PagerTemplate>
                <table>
                    <tr>
                        <td>
                            <asp:LinkButton ID="LinkButton1" runat="server" Text="Previous" CommandName="Page" CommandArgument="Prev"/>
                            <asp:LinkButton ID="LinkButton2" runat="server" Text="Next" CommandName="Page" CommandArgument="Next"/>
                        </td>
                        
                        <td>
                          Page No  <asp:Label ID="l1" runat="server"/>
                           Total Page <asp:Label ID="l2" runat="server"/>
                        </td>

                    </tr>


                </table>


            </PagerTemplate>
            <PagerSettings Mode="NextPrevious" Position="Bottom" />



        </asp:FormView>
       
    </form>
</body>
</html>

Code Behind page

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

public partial class Default5 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            formviewload();
        }
    }

    private void formviewload()
    {
        //throw new NotImplementedException();
        SqlConnection con = new SqlConnection();
        con.ConnectionString =ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
        con.Open();
        SqlCommand cmd= new SqlCommand();
        cmd.CommandText ="select * from [Employee]";
        cmd.Connection =con;
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        DataSet ds = new DataSet();
        da.Fill(ds);
        FormView1.DataSource =ds;
        FormView1.DataBind();

    }
    protected void FormView1_DataBound(object sender, EventArgs e)
    {
        FormViewRow pagerrow = FormView1.BottomPagerRow;
        Label pageno = (Label)pagerrow.Cells[0].FindControl("l1");
        Label totalpage = (Label)pagerrow.Cells[0].FindControl("l2");
        if ((pageno!=null) && (totalpage!=null))
        {
            int pagen = FormView1.PageIndex +1;
            int total = FormView1.PageCount;
            pageno.Text = pagen.ToString();
            totalpage.Text = total.ToString();

        }
    }
    protected void FormView1_PageIndexChanging(object sender, FormViewPageEventArgs e)
    {
        FormView1.PageIndex = e.NewPageIndex;
        formviewload();

    }
}

Code generates the following output

Pager Template in FormView Example of ASP.NET C#


Monday, May 9, 2016

How to Design Country, State, and City DropDownList using SqlDataSource

In this article i will show you, How to bind Dropdownlist with the Country, State and City table using SqlDataSource. We all that If among tables are related to each other then we can show among tables one by one on indexChanged event. So, First of all design tables following ways:

[CountryTable]
CountryId  int primary_key Identity(1,1)
Country_Name nvarchar(100)

[State]
StateId int primary_key Identity(1,1)
State_Name nvarchar(100)
CountryId int

[City]
CityId int primary_key Identity(1,1)
City_Name nvarchar(100)
StateId int


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

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
   
        Select Country :
        <asp:DropDownList ID="DropDownList1" runat="server" AppendDataBoundItems="True" AutoPostBack="True" DataSourceID="SqlDataSource1" DataTextField="CountryName" DataValueField="CountryId" Height="19px" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged" Width="150px">
            <asp:ListItem Value="0">Select</asp:ListItem>
        </asp:DropDownList>
        <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>" SelectCommand="SELECT * FROM [Country]"></asp:SqlDataSource>
        <br />
        <br />
        Select State :&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
        <asp:DropDownList ID="DropDownList2" runat="server" AppendDataBoundItems="True" AutoPostBack="True" DataSourceID="SqlDataSource2" DataTextField="StateName" DataValueField="StateId" Height="19px" OnSelectedIndexChanged="DropDownList2_SelectedIndexChanged" Width="150px">
            <asp:ListItem Value="0">Select</asp:ListItem>
        </asp:DropDownList>
        <asp:SqlDataSource ID="SqlDataSource2" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>" SelectCommand="SELECT * FROM [State] WHERE ([CountryId] = @CountryId)">
            <SelectParameters>
                <asp:ControlParameter ControlID="DropDownList1" Name="CountryId" PropertyName="SelectedValue" Type="Int32" />
            </SelectParameters>
        </asp:SqlDataSource>
        <br />
        <br />
        Select City :&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <asp:DropDownList ID="DropDownList3" runat="server" AppendDataBoundItems="True" DataSourceID="SqlDataSource3" DataTextField="CityName" DataValueField="CityId" Height="19px" Width="150px">
            <asp:ListItem Value="0">Select</asp:ListItem>
        </asp:DropDownList>
        <asp:SqlDataSource ID="SqlDataSource3" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>" SelectCommand="SELECT * FROM [City] WHERE ([StateId] = @StateId)">
            <SelectParameters>
                <asp:ControlParameter ControlID="DropDownList2" Name="StateId" PropertyName="SelectedValue" Type="Int32" />
            </SelectParameters>
        </asp:SqlDataSource>
   
    </div>
    </form>
</body>
</html>

© Copyright 2013 Computer Programming | All Right Reserved