7a. Create a web application to display Databinding using dropdownlist control.

Program:

Default .aspx


<%@PageLanguage="C#"AutoEventWireup="true"CodeBehind="Default . aspx.cs" Inherits="WebApplication3._Default "%>
<!DOCTYPEhtmlPUBLIC"-//W3C//DTDXHTML1.0Transitional//EN" " http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional . dtd" >
<htmlxmlns="http://www.w3.org/1999/xhtml ">
<headrunat ="server " >
<title>UntitledPage</title>
</head>
<body >
<formid="form1"runat ="server " >
<div >
<asp:DropDownListID="DropDownList1"runat ="server " >
</asp:DropDownList >
<br/>
<br/>
</div >
<asp:ButtonID="Button1"runat ="server "onclick="Button1_Click"
Text ="ClickMe..!"/>
<br/>
<br/>
<asp:LabelID="Label1"runat ="server "Text ="TheCountryyouhaveselectedis:"></asp:Label >
</form>
</body >
</html >


Default.aspx.cs


using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security ;
using System.Web.UI ;
using System.Web.UI . HtmlControls;
using System.Web.UI . WebControls;
using System.Web.UI . WebControls.WebParts;
using System.Xml . Linq;
using System.Data.Sql ;
using System.Data.SqlClient ;
using System.Data.SqlTypes;
namespaceWebApplication3
{
publicpartialclass_Default:System.Web.UI . Page
{
SqlConnectionsqlcon=newSqlConnection( @"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\BNB\Documents\VisualStudio 2008\Projects\WebApplication3\WebApplication3\App_Data\Database1.mdf ; Integrated Security=True;UserInstance=True" );
protectedvoidPage_Load(objectsender , EventArgse)
{
if(IsPostBack==false)
{
sqlcon.Open();
SqlCommandcmd=newSqlCommand( " SelectCityfromDB1" , sqlcon);
SqlDataReaderreader=cmd.ExecuteReader();
DropDownList1.DataSource=reader ;
DropDownList1.DataTextField="City " ;
DropDownList1.DataBind();
reader . Close();
sqlcon.Close();
}
}
protectedvoidButton1_Click(objectsender , EventArgse)
{
Label1.Text="Youhaveselected:"+DropDownList1.SelectedValue;
}
}
}

Comments