You are on page 1of 68

Show Bind Data to Asp.net Dropdownlist from Database in C#, VB.

NET
Introduction: Here I will explain how to bind or show data in dropdownlist from database in asp.net using C#.net andVB.NET. Description: In previous posts I explained many articles relating asp.net, jQuery, SQL Server, JavaScript. Now I will explain how to bind or show data in dropdownlist from database in asp.net using C#.net and VB.NET. Before implement this example first design one table UserInformation in your database as shown below Column Name UserId UserName Location Data Type Int (set Identity=true) varchar(50) Varchar(50) Allow Nulls No Yes Yes

Once table designed in database write the following code in your aspx page

<html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>how to show data in dropdownlist from database in asp.net</title> </head> <body> <form id="form1" runat="server"> <div> <b>Selected UserName:</b> <asp:DropDownList ID="ddlCountry" runat="server" /> </div> </form> </body> </html> Now add the following namespaces in code behind C# Code

using System; using System.Data; using System.Data.SqlClient; using System.Web.UI.WebControls; After add namespaces write the following code in code behind

protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) {

BindContrydropdown(); } } /// <summary> /// Bind COuntrydropdown /// </summary> protected void BindContrydropdown() { //conenction path for database using (SqlConnection con = new SqlConnection("Data Source=SureshDasari;Integrated Security=true;Initial Catalog=MySampleDB")) { con.Open(); SqlCommand cmd = new SqlCommand("Select UserId,UserName FROM UserInformation", con); SqlDataAdapter da = new SqlDataAdapter(cmd); DataSet ds = new DataSet(); da.Fill(ds); ddlCountry.DataSource = ds; ddlCountry.DataTextField = "UserName"; ddlCountry.DataValueField = "UserId"; ddlCountry.DataBind(); ddlCountry.Items.Insert(0, new ListItem("--Select--", "0")); con.Close(); } } VB.NET Code

Imports System.Data Imports System.Data.SqlClient Imports System.Web.UI.WebControls Partial Class VBSample Inherits System.Web.UI.Page Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load If Not IsPostBack Then BindContrydropdown() End If End Sub ''' <summary> ''' Bind COuntrydropdown ''' </summary> Protected Sub BindContrydropdown() 'conenction path for database Using con As New SqlConnection("Data Source=SureshDasari;Integrated Security=true;Initial Catalog=MySampleDB") con.Open() Dim cmd As New SqlCommand("Select UserId,UserName FROM UserInformation", con) Dim da As New SqlDataAdapter(cmd) Dim ds As New DataSet() da.Fill(ds) ddlCountry.DataSource = ds ddlCountry.DataTextField = "UserName" ddlCountry.DataValueField = "UserId" ddlCountry.DataBind() ddlCountry.Items.Insert(0, New ListItem("--Select--", "0")) con.Close() End Using End Sub End Class Demo

If you want to learn more dropdownlist articles check this

How to Fill Country,State,Cities in the DropDownList in asp.net C#,VB.Net


Introduction: In this article i am going to explain the following:

How to Bind /Load /Fill Countries, States and Cities in the DropDownList fromSql
Server Database in asp.net using C# and Vb.net language How to Fill another DropDownList based on DropDownList item selection e.g. here in this example On the basis of selected Country corresponding States will be filled in the State DropDownList and on the basis of selected state corresponding cities will be filled in City DropDownList. Cascade DropDownList example to fill city,state and country. In previous articles i explained How to Get city, state and country based on zip code using Google map API in asp.net and How to fill dropdownlist with days, month and year in asp.net(C#, VB) and Fill CheckBoxList based on DropDownList selection and Example to Validate DropDownList using jQuery in asp.net.

Let's create the application to understand. First create a Database in Sql Server and name it "Emp_DB" or whatever you want. Now we need to create table for County, State and City. Insert

some data in all the tables as shown below.

Create the table and name it Tbl_Country

Column Name Country_Id_Pk Country_Name

Data type int varchar(10 0)

Set is identity=yes

Tbl_Country table data

Country_Id_P k 1 2

Country_Na me India Australia

Create the table and name it Tbl_ State

Column Name State_Id_pk State_Name

Data type int Set is identity=yes

varchar(10 0) country_Id_Fk int


Tbl_State table data

State_Id_p k 1 2 3 4

State_Name Haryana Punjab Himachal Pradesh Queensland

country_Id_ Fk 1 1 1 2

Create the table and name it Tbl_City

Column Name City_Id_Pk

Data type int Set is identity=yes

City_Name varchar(10

State_Id_Fk

0) int

Tbl_City table data

City_Id_P City_Nam k e 1 Panchkula 2 Kalka 3 Ambala 4 Moga 5 Bathinda 6 Shimla 7 kasauli 8 Brisbane 9 Townsville

State_Id_ Fk 1 1 1 2 2 3 3 4 4

In the web.config file create the connection string in <connectionString> element as: <connectionStrings> <add name="conStr" connectionString="Data Source=LocalServer;Initial Catalog=Emp_DB;Integrated Security=True"/> </connectionStrings> Note: Replace the Data Source and Initial Catalog(i.e. Database name) as per your application. In the design page(.aspx) Place 3 DropDownList controls from the visual studios toolbar and design the form as:

<fieldset style="width:340px;"> <legend>Fill City,State and Country DropDownList in asp.net</legend> <table> <tr> <td width="40%">Select Country:</td> <td><asp:DropDownList ID="ddlCountry" runat="server" AutoPostBack="True" onselectedindexchanged="ddlCountry_SelectedIndexChanged" Width="187px"></asp :DropDownList></td> </tr> <tr> <td>Select State:</td>

<td><asp:DropDownList ID="ddlState" runat="server" AutoPostBack="True" onselectedindexchanged="ddlState_SelectedIndexChanged" Width="187px"></asp:D ropDownList></td> </tr> <tr> <td>Select City:</td> <td> <asp:DropDownList ID="ddlCity" runat="server" Width="187px"></asp:DropDownList> </td> </tr> </table> </fieldset>

C#.Net Code

to Fill Country, State and cities in the DropDownList.

In the Code behind file (.aspx.cs) write the code as: First include the following namespaces: using System.Data; using System.Data.SqlClient; using System.Configuration; Then write the code as: //Creating and initializing connection object. SqlConnection con = newSqlConnection(ConfigurationManager.ConnectionStrings["conStr"].ConnectionString); protected void Page_Load(object sender, EventArgs e) { //Checking Connection State and opening if closed if (con.State == ConnectionState.Closed) { con.Open(); } if (!Page.IsPostBack) { //Call countries DropDownList on page load event BindContriesDropDownList(); } }

protected void ddlCountry_SelectedIndexChanged(object sender, EventArgs e) { try { int CountryId = Convert.ToInt32(ddlCountry.SelectedValue); //Select all States corresponding to the selected Country SqlDataAdapter adp = new SqlDataAdapter("select * from Tbl_State where Country_ID_Fk=" + CountryId, con); DataSet ds = new DataSet(); adp.Fill(ds); ddlState.DataSource = ds; ddlState.DataTextField = "State_Name"; ddlState.DataValueField = "State_Id_Pk"; ddlState.DataBind(); ddlState.Items.Insert(0, new ListItem("--Select--", "0")); //If State is not selected then clear City DropDownList also if (ddlState.SelectedValue == "0") { ddlCity.Items.Clear(); ddlCity.Items.Insert(0, new ListItem("--Select--", "0")); } } catch (Exception ex) { //Printing any exception if occcured. Response.Write("Error occured: " + ex.Message.ToString()); } finally { //Close the connection con.Close(); } } protected void ddlState_SelectedIndexChanged(object sender, EventArgs e) { try { int StateId = Convert.ToInt32(ddlState.SelectedValue);

//Select all Cities corresponding to the selected State SqlDataAdapter adp = new SqlDataAdapter("select * from Tbl_City where State_ID_Fk=" + StateId, con); DataSet ds = new DataSet(); adp.Fill(ds); ddlCity.DataSource = ds; ddlCity.DataTextField = "City_Name"; ddlCity.DataValueField = "City_id_pk"; ddlCity.DataBind(); ddlCity.Items.Insert(0, new ListItem("--Select--", "0")); } catch (Exception ex) { Response.Write("Error occured : " + ex.Message.ToString()); } finally { con.Close(); } } protected void BindContriesDropDownList() { try { SqlDataAdapter adp = new SqlDataAdapter("select * from Tbl_Country", con); DataSet ds = new DataSet(); adp.Fill(ds); ddlCountry.DataSource = ds; ddlCountry.DataTextField = "Country_Name"; ddlCountry.DataValueField = "Country_Id_Pk"; ddlCountry.DataBind(); ddlCountry.Items.Insert(0, new ListItem("--Select--", "0")); ddlState.Items.Insert(0, new ListItem("--Select--", "0")); ddlCity.Items.Insert(0, new ListItem("--Select--", "0")); } catch (Exception ex) {

Response.Write("Error occured : " + ex.Message.ToString()); } finally { con.Close(); } }

VB.Net Code to Fill Country, State and cities in the DropDownList.


In the design page(.aspx) Place 3 DropDownList controls from the visual studios toolbar and design the page as: <fieldset style="width:340px;"> <legend>Fill City,State and Country DropDownList in asp.net</legend> <table> <tr> <td width="40%">Select Country:</td> <td><asp:DropDownList ID="ddlCountry" runat="server" AutoPostBack="True" Width="187px"></asp:DropDownList></td> </tr> <tr> <td>Select State:</td> <td><asp:DropDownList ID="ddlState" runat="server" AutoPostBack="True" Width="187px"></asp:DropDownList></td> </tr> <tr> <td>Select City:</td> <td> <asp:DropDownList ID="ddlCity" runat="server" Width="187px"></asp:DropDownList> </td> </tr> </table> </fieldset>

In the Code behind file (.aspx.vb) write the code as: First import the following namerspaces: Imports System.Data

Imports System.Data.SqlClient Imports System.Configuration Then write the code as: 'Creating and initializing connection object. Dim con As NewSqlConnection(ConfigurationManager.ConnectionStrings("conStr").Connectio nString) Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load 'Checking Connection State and opening if closed If con.State = ConnectionState.Closed Then con.Open() End If If Not Page.IsPostBack Then 'Call countries DropDownList on page load event BindContriesDropDownList() End If End Sub Protected Sub ddlCountry_SelectedIndexChanged(sender As Object, e AsSystem.EventArgs) Handles ddlCountry.SelectedIndexChanged Try Dim CountryId As Integer = Convert.ToInt32(ddlCountry.SelectedValue) 'Select all States corresponding to the selected Country Dim adp As New SqlDataAdapter("select * from Tbl_State where Country_ID_Fk=" & CountryId, con) Dim ds As New DataSet() adp.Fill(ds) ddlState.DataSource = ds ddlState.DataTextField = "State_Name" ddlState.DataValueField = "State_Id_Pk" ddlState.DataBind() ddlState.Items.Insert(0, New ListItem("--Select--", "0")) 'If State is not selected then clear City DropDownList also If ddlState.SelectedValue = "0" Then ddlCity.Items.Clear() ddlCity.Items.Insert(0, New ListItem("--Select--", "0")) End If

Catch ex As Exception 'Printing any exception if occcured. Response.Write("Error occured: " & ex.Message.ToString()) Finally 'Close the connection con.Close() End Try End Sub Protected Sub ddlState_SelectedIndexChanged(sender As Object, e As System.EventArgs)Handles ddlState.SelectedIndexChanged Try Dim StateId As Integer = Convert.ToInt32(ddlState.SelectedValue) 'Select all Cities corresponding to the selected State Dim adp As New SqlDataAdapter("select * from Tbl_City where State_ID_Fk=" & StateId, con) Dim ds As New DataSet() adp.Fill(ds) ddlCity.DataSource = ds ddlCity.DataTextField = "City_Name" ddlCity.DataValueField = "City_id_pk" ddlCity.DataBind() ddlCity.Items.Insert(0, New ListItem("--Select--", "0")) Catch ex As Exception Response.Write("Error occured : " & ex.Message.ToString()) Finally con.Close() End Try End Sub Protected Sub BindContriesDropDownList() Try Dim adp As New SqlDataAdapter("select * from Tbl_Country", con) Dim ds As New DataSet() adp.Fill(ds) ddlCountry.DataSource = ds ddlCountry.DataTextField = "Country_Name" ddlCountry.DataValueField = "Country_Id_Pk"

ddlCountry.DataBind() ddlCountry.Items.Insert(0, New ListItem("--Select--", "0")) ddlState.Items.Insert(0, New ListItem("--Select--", "0")) ddlCity.Items.Insert(0, New ListItem("--Select--", "0")) Catch ex As Exception Response.Write("Error occured : " & ex.Message.ToString()) Finally con.Close() End Try End Sub Now over to you: "If you like my work; you can appreciate by leaving your comments, hitting Facebook like button, following on Google+, Twitter, Linked in and Pinterest, stumbling my posts on stumble upon and subscribing for receiving free updates directly to your inbox . Stay tuned and stay connected for more technical updates."

How to Fill Country,State,Cities in the DropDownList in asp.net C#,VB.Net


Introduction: In this article i am going to explain the following:

How to Bind /Load /Fill Countries, States and Cities in the DropDownList fromSql
Server Database in asp.net using C# and Vb.net language How to Fill another DropDownList based on DropDownList item selection e.g. here in this example On the basis of selected Country corresponding States will be filled in the State DropDownList and on the basis of selected state corresponding cities will be filled in City DropDownList. Cascade DropDownList example to fill city,state and country. In previous articles i explained How to Get city, state and country based on zip code using Google map API in asp.net and How to fill dropdownlist with days, month and year in asp.net(C#, VB) and Fill CheckBoxList based on DropDownList selection and Example to Validate DropDownList using jQuery in asp.net.

Let's create the application to understand. First create a Database in Sql Server

and name it "Emp_DB" or whatever you want. Now we need to create table for County, State and City. Insert some data in all the tables as shown below.

Create the table and name it Tbl_Country

Column Name Country_Id_Pk

Data type int

Set is identity=yes

Country_Name varchar(1 00)


Tbl_Country table data

Country_Id_ Pk 1 2

Country_Na me India Australia

Create the table and name it Tbl_ State

Column Name State_Id_pk

Data type int

Set is identity=yes

State_Name varchar(1 00) country_Id_F int k


Tbl_State table data

State_Id_ pk 1 2 3 4

State_Name Haryana Punjab Himachal Pradesh Queensland

country_Id _Fk 1 1 1 2

Create the table and name it Tbl_City

Column Name

Data type

City_Id_Pk

int

Set is identity=yes

City_Name varchar(1 00) State_Id_F int k

Tbl_City table data

City_Id_ City_Na Pk me 1 Panchkula 2 Kalka 3 Ambala 4 Moga 5 Bathinda 6 Shimla 7 kasauli 8 Brisbane 9 Townsville

State_Id _Fk 1 1 1 2 2 3 3 4 4

In the web.config file create the connection string in <connectionString> element as: <connectionStrings> <add name="conStr" connectionString="Data Source=LocalServer;Initial Catalog=Emp_DB;Integrated Security=True"/> </connectionStrings> Note: Replace the Data Source and Initial Catalog(i.e. Database name) as per your application. In the design page(.aspx) Place 3 DropDownList controls from the visual studios toolbar and design the form as:

<fieldset style="width:340px;"> <legend>Fill City,State and Country DropDownList in asp.net</legend> <table> <tr> <td width="40%">Select Country:</td> <td><asp:DropDownList ID="ddlCountry" runat="server" AutoPostBack="True"

onselectedindexchanged="ddlCountry_SelectedIndexChanged" Width="187 px"></asp:DropDownList></td> </tr> <tr> <td>Select State:</td> <td><asp:DropDownList ID="ddlState" runat="server" AutoPostBack="True" onselectedindexchanged="ddlState_SelectedIndexChanged" Width="187px "></asp:DropDownList></td> </tr> <tr> <td>Select City:</td> <td> <asp:DropDownList ID="ddlCity" runat="server" Width="187px"></asp:D ropDownList></td> </tr> </table> </fieldset>

C#.Net Code

to Fill Country, State and cities in the DropDownList.

In the Code behind file (.aspx.cs) write the code as: First include the following namespaces: using System.Data; using System.Data.SqlClient; using System.Configuration; Then write the code as: //Creating and initializing connection object. SqlConnection con = newSqlConnection(ConfigurationManager.ConnectionStrings["conStr"].Connection String); protected void Page_Load(object sender, EventArgs e) { //Checking Connection State and opening if closed if (con.State == ConnectionState.Closed) { con.Open(); }

if (!Page.IsPostBack) { //Call countries DropDownList on page load event BindContriesDropDownList(); } } protected void ddlCountry_SelectedIndexChanged(object sender, EventArgs e) { try { int CountryId = Convert.ToInt32(ddlCountry.SelectedValue); //Select all States corresponding to the selected Country SqlDataAdapter adp = new SqlDataAdapter("select * from Tbl_State where Country_ID_Fk=" + CountryId, con); DataSet ds = new DataSet(); adp.Fill(ds); ddlState.DataSource = ds; ddlState.DataTextField = "State_Name"; ddlState.DataValueField = "State_Id_Pk"; ddlState.DataBind(); ddlState.Items.Insert(0, new ListItem("--Select--", "0")); //If State is not selected then clear City DropDownList also if (ddlState.SelectedValue == "0") { ddlCity.Items.Clear(); ddlCity.Items.Insert(0, new ListItem("--Select--", "0")); } } catch (Exception ex) { //Printing any exception if occcured. Response.Write("Error occured: " + ex.Message.ToString()); } finally { //Close the connection con.Close(); }

} protected void ddlState_SelectedIndexChanged(object sender, EventArgs e) { try { int StateId = Convert.ToInt32(ddlState.SelectedValue); //Select all Cities corresponding to the selected State SqlDataAdapter adp = new SqlDataAdapter("select * from Tbl_City where State_ID_Fk=" + StateId, con); DataSet ds = new DataSet(); adp.Fill(ds); ddlCity.DataSource = ds; ddlCity.DataTextField = "City_Name"; ddlCity.DataValueField = "City_id_pk"; ddlCity.DataBind(); ddlCity.Items.Insert(0, new ListItem("--Select--", "0")); } catch (Exception ex) { Response.Write("Error occured : " + ex.Message.ToString()); } finally { con.Close(); } } protected void BindContriesDropDownList() { try { SqlDataAdapter adp = new SqlDataAdapter("select * from Tbl_Country", con); DataSet ds = new DataSet(); adp.Fill(ds); ddlCountry.DataSource = ds; ddlCountry.DataTextField = "Country_Name"; ddlCountry.DataValueField = "Country_Id_Pk"; ddlCountry.DataBind();

ddlCountry.Items.Insert(0, new ListItem("--Select--", "0")); ddlState.Items.Insert(0, new ListItem("--Select--", "0")); ddlCity.Items.Insert(0, new ListItem("--Select--", "0")); } catch (Exception ex) { Response.Write("Error occured : " + ex.Message.ToString()); } finally { con.Close(); } }

VB.Net Code to Fill Country, State and cities in the DropDownList.


In the design page(.aspx) Place 3 DropDownList controls from the visual studios toolbar and design the page as: <fieldset style="width:340px;"> <legend>Fill City,State and Country DropDownList in asp.net</legend> <table> <tr> <td width="40%">Select Country:</td> <td><asp:DropDownList ID="ddlCountry" runat="server" AutoPostBack="True" Width="187px"></asp:DropDownList></td> </tr> <tr> <td>Select State:</td> <td><asp:DropDownList ID="ddlState" runat="server" AutoPostBack="True" Width="187px"></asp:DropDownList></td> </tr> <tr> <td>Select City:</td> <td> <asp:DropDownList ID="ddlCity" runat="server" Width="187px"></asp:D ropDownList></td> </tr> </table>

</fieldset>

In the Code behind file (.aspx.vb) write the code as: First import the following namerspaces: Imports System.Data Imports System.Data.SqlClient Imports System.Configuration Then write the code as: 'Creating and initializing connection object. Dim con As NewSqlConnection(ConfigurationManager.ConnectionStrings("conStr"). ConnectionString) Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load 'Checking Connection State and opening if closed If con.State = ConnectionState.Closed Then con.Open() End If If Not Page.IsPostBack Then 'Call countries DropDownList on page load event BindContriesDropDownList() End If End Sub Protected Sub ddlCountry_SelectedIndexChanged(sender As Object, e AsSystem.EventArgs) Handles ddlCountry.SelectedIndexChanged Try Dim CountryId As Integer = Convert.ToInt32(ddlCountry.SelectedValue) 'Select all States corresponding to the selected Country Dim adp As New SqlDataAdapter("select * from Tbl_State where Country_ID_Fk=" & CountryId, con) Dim ds As New DataSet() adp.Fill(ds) ddlState.DataSource = ds ddlState.DataTextField = "State_Name" ddlState.DataValueField = "State_Id_Pk" ddlState.DataBind()

ddlState.Items.Insert(0, New ListItem("--Select--", "0")) 'If State is not selected then clear City DropDownList also If ddlState.SelectedValue = "0" Then ddlCity.Items.Clear() ddlCity.Items.Insert(0, New ListItem("--Select--", "0")) End If Catch ex As Exception 'Printing any exception if occcured. Response.Write("Error occured: " & ex.Message.ToString()) Finally 'Close the connection con.Close() End Try End Sub Protected Sub ddlState_SelectedIndexChanged(sender As Object, e As System.EventArgs)Handles ddlState.SelectedIndexChanged Try Dim StateId As Integer = Convert.ToInt32(ddlState.SelectedValue) 'Select all Cities corresponding to the selected State Dim adp As New SqlDataAdapter("select * from Tbl_City where State_ID_Fk=" & StateId, con) Dim ds As New DataSet() adp.Fill(ds) ddlCity.DataSource = ds ddlCity.DataTextField = "City_Name" ddlCity.DataValueField = "City_id_pk" ddlCity.DataBind() ddlCity.Items.Insert(0, New ListItem("--Select--", "0")) Catch ex As Exception Response.Write("Error occured : " & ex.Message.ToString()) Finally con.Close() End Try End Sub Protected Sub BindContriesDropDownList() Try

Dim adp As New SqlDataAdapter("select * from Tbl_Country", con) Dim ds As New DataSet() adp.Fill(ds) ddlCountry.DataSource = ds ddlCountry.DataTextField = "Country_Name" ddlCountry.DataValueField = "Country_Id_Pk" ddlCountry.DataBind() ddlCountry.Items.Insert(0, New ListItem("--Select--", "0")) ddlState.Items.Insert(0, New ListItem("--Select--", "0")) ddlCity.Items.Insert(0, New ListItem("--Select--", "0")) Catch ex As Exception Response.Write("Error occured : " & ex.Message.ToString()) Finally con.Close() End Try End Sub Now over to you: "If you like my work; you can appreciate by leaving your comments, hitting Facebook like button, following on Google+, Twitter, Linked in and Pinterest, stumbling my posts on stumble upon and subscribing for receiving free updates directly to your inbox . Stay tuned and stay connected for more technical updates."

Create registration form and send confirmation email to new registered users in asp.net | Activate or approve user account by activation link in email address.
Introduction: In this article I am going to explain with example How to create registration form and approve newly registered user by sending them account activation link on their email address in asp.net with both C#.Net and VB.Net languages.

Description: The concept is simple as mentioned below. First user will fill the form having Name, Email Id, Address and

Contact Number field. This information will be stored in the Sql server database table where a field Is_Approved is set to 0 i.e. false by default. Also email id, and the user id based on email id is set in the query string parameters and sent to the email address of the newly registered user as an activation link. When user check his email and click on the activation link then he will be redirected to the "ActivateAccount.aspx" page where User id and email Id from the query string will be verified and the Is_Approved field in the sql server table is set to 1 i.e. True. Now he is an approved user and authorized to log in. Implementation: lets create an asp.net web application to understand the concept. First of all create a database e.g. MyDataBase in Sql server and create a table with the column and the data type as shown and name it Tb_Registration Note: I have set the data type of the Is_Approved field to bit and set its default value to 0 i.e. false. It means whenever a new record is inserted in the table the Is_Approved will be 0. So the new users need to get their account approved by clicking on the activation link in their email address. In the web.config file create the connection string to connect your asp.net application to the Sql server database as: <connectionStrings> <add name="conStr" connectionString="Data Source=lalit;Initial Catalog=MyDataBase;Integrated Security=True"/> </connectionStrings> Note: Replace the Data Source and Initial Catalog(i.e. DataBase Name) as per your application. Source Code: Add a page and name it Registration.aspx and design the page as: <div> <fieldset style="width:350px;"> <legend>Registeration page</legend> <table> <tr> <td>Name *: </td><td>

<asp:TextBox ID="txtName" runat="server"></asp:TextBox><br /><asp:RequiredFieldV alidator ID="rfvName" runat="server" ErrorMessage="Please enter Name" ControlToValidate="txtName" Display="Dynamic" ForeColor="#FF3300" SetFocusOnError="True"></asp:RequiredFieldValidator></td> </tr> <tr> <td>Email Id: * </td><td> <asp:TextBox ID="txtEmailId" runat="server"></asp:TextBox><br /> <asp:RequiredFieldValidator ID="rfvEmailId" runat="server" ControlToValidate="txtEmailId" Display="Dynamic" ErrorMessage="Please enter Email Id" ForeColor="Red" SetFocusOnError="True"></asp:RequiredFieldValidator> <asp:RegularExpressionValidator ID="rgeEmailId" runat="server" ControlToValidate="txtEmailId" Display="Dynamic" ErrorMessage="Please enter valid email id format" ForeColor="Red" SetFocusOnError="True" ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+ ([-.]\w+)*"></asp:RegularExpressionValidator> </td> </tr> <tr> <td>Address : </td><td> <asp:TextBox ID="txtAddress" runat="server"></asp:TextBox></td> </tr> <tr> <td>Contact No.</td><td>

<asp:TextBox ID="txtContactNo" runat="server"></asp:TextBox></td> </tr> <tr> <td>&nbsp;</td><td> <asp:Button ID="btnSubmit" runat="server" Text="Submit" onclick="btnSubmit_Click" /></td> </tr> </table> </fieldset> </div> C#.Net Code for Registration.aspx In the code behind file (Registration.aspx.cs) write the code as: using System.Data; using System.Data.SqlClient; using System.Configuration; using System.Text; using System.Net; using System.Net.Mail; SqlConnection con = newSqlConnection(ConfigurationManager.ConnectionStrings["conStr"].ConnectionString); protected void btnSubmit_Click(object sender, EventArgs e) { MailMessage msg; SqlCommand cmd = new SqlCommand(); string ActivationUrl = string.Empty; string emailId = string.Empty;

try { cmd = new SqlCommand("insert into Tb_Registration (Name,EmailId,Address,ContactNo) values (@Name,@EmailId,@Address,@ContactNo) ", con); cmd.Parameters.AddWithValue("@Name", txtName.Text.Trim()); cmd.Parameters.AddWithValue("@EmailId", txtEmailId.Text.Trim()); cmd.Parameters.AddWithValue("@Address", txtAddress.Text.Trim()); cmd.Parameters.AddWithValue("@ContactNo", txtContactNo.Text.Trim()); if (con.State == ConnectionState.Closed) { con.Open(); } cmd.ExecuteNonQuery(); //Sending activation link in the email msg = new MailMessage(); SmtpClient smtp = new SmtpClient(); emailId = txtEmailId.Text.Trim(); //sender email address msg.From = new MailAddress("YourGmailEmailId@gmail.com"); //Receiver email address msg.To.Add(emailId); msg.Subject = "Confirmation email for account activation"; //For testing replace the local host path with your lost host path and while making online replace with your website domain name ActivationUrl = Server.HtmlEncode("http://localhost:8665/MySampleApplication/ActivateAccount.aspx? UserID=" + FetchUserId(emailId) + "&EmailId=" + emailId);

msg.Body = "Hi " + txtName.Text.Trim() + "!\n" + "Thanks for showing interest and registring in <a href='http://www.webcodeexpert.com'> webcodeexpert.com<a> " + " Please <a href='" + ActivationUrl + "'>click here to activate</a> your account and enjoy our services. \nThanks!"; msg.IsBodyHtml = true; smtp.Credentials = new NetworkCredential("YourGmailEmailId@gmail.com","YourGmailPassword"); smtp.Port = 587; smtp.Host = "smtp.gmail.com"; smtp.EnableSsl = true; smtp.Send(msg); clear_controls(); ScriptManager.RegisterStartupScript(this, this.GetType(), "Message", "alert('Confirmat ion Link to activate your account has been sent to your email address');", true); } catch (Exception ex) { ScriptManager.RegisterStartupScript(this, this.GetType(), "Message", "alert('Error occured : " + ex.Message.ToString() + "');", true); return; } finally { ActivationUrl = string.Empty; emailId = string.Empty; con.Close(); cmd.Dispose();

} } private string FetchUserId(string emailId) { SqlCommand cmd = new SqlCommand(); cmd = new SqlCommand("SELECT UserId FROM Tb_Registration WHERE EmailId=@EmailId", con); cmd.Parameters.AddWithValue("@EmailId", emailId); if (con.State == ConnectionState.Closed) { con.Open(); } string UserID = Convert.ToString(cmd.ExecuteScalar()); con.Close(); cmd.Dispose(); return UserID; } private void clear_controls() { txtName.Text = string.Empty; txtEmailId.Text = string.Empty; txtAddress.Text = string.Empty; txtContactNo.Text = string.Empty; txtName.Focus(); } Add a new page and name it ActivateAccount.aspx. This page will be opened when

new registered user click on the activate account link in his email. On the page load it will check email id and user id from the query string and then update the "Is_Approved" column to 1 i.e. True. Then you can redirect him to your login page to log in. Code for ActivateAccount.aspx page In the code behind file (ActivateAccount.aspx.cs) write the code as: using System.Data; using System.Data.SqlClient; using System.Configuration; protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { ActivateMyAccount(); } } private void ActivateMyAccount() { SqlConnection con = new SqlConnection(); SqlCommand cmd = new SqlCommand(); try { con = newSqlConnection(ConfigurationManager.ConnectionStrings["conStr"].ConnectionString); if ((!string.IsNullOrEmpty(Request.QueryString["UserID"])) & (! string.IsNullOrEmpty(Request.QueryString["EmailId"]))) { //approve account by setting Is_Approved to 1 i.e. True in the sql server table cmd = new SqlCommand("UPDATE Tb_Registration SET Is_Approved=1 WHERE

UserID=@UserID AND EmailId=@EmailId", con); cmd.Parameters.AddWithValue("@UserID", Request.QueryString["UserID"]); cmd.Parameters.AddWithValue("@EmailId", Request.QueryString["EmailId"]); if (con.State == ConnectionState.Closed) { con.Open(); } cmd.ExecuteNonQuery(); Response.Write("You account has been activated. You can <a href='Login.aspx'>Login</a> now! "); } } catch (Exception ex) { ScriptManager.RegisterStartupScript(this, this.GetType(), "Message", "alert('Error occured : " + ex.Message.ToString() + "');", true); return; } finally { con.Close(); cmd.Dispose(); } } VB.Net Section: Source code of Registration.aspx

Design the Registration.aspx page as in C#.Net section but replace the line <asp:ButtonID="btnSubmit" runat="server" Text="Submit" onclick="btnSubmit_ Click" /> With <asp:Button ID="btnSubmit" runat="server" Text="Submit" /> VB.Net Code for Registration.aspx page In the code behind file (Registration.aspx.vb) write the code as: Imports System.Data Imports System.Data.SqlClient Imports System.Configuration Imports System.Text Imports System.Net Imports System.Net.Mail Dim con As NewSqlConnection(ConfigurationManager.ConnectionStrings("conStr").Connect ionString) Protected Sub btnSubmit_Click(sender As Object, e As System.EventArgs) HandlesbtnSubmit.Click Dim msg As MailMessage Dim cmd As New SqlCommand() Dim ActivationUrl As String = String.Empty Dim emailId As String = String.Empty Try cmd = New SqlCommand("insert into Tb_Registration (Name,EmailId,Address,ContactNo) values (@Name,@EmailId,@Address,@ContactNo) ", con) cmd.Parameters.AddWithValue("@Name", txtName.Text.Trim()) cmd.Parameters.AddWithValue("@EmailId", txtEmailId.Text.Trim()) cmd.Parameters.AddWithValue("@Address", txtAddress.Text.Trim()) cmd.Parameters.AddWithValue("@ContactNo", txtContactNo.Text.Trim())

If con.State = ConnectionState.Closed Then con.Open() End If cmd.ExecuteNonQuery() Sending activation link in the email msg = New MailMessage() Dim smtp As New SmtpClient() emailId = txtEmailId.Text.Trim() 'sender email address msg.From = New MailAddress("YourGmailEmailId@gmail.com") 'Receiver email address msg.[To].Add(emailId) msg.Subject = "Confirmation email for account activation" 'For testing replace the local host path with your lost host path and while making online replace with your website domain name ActivationUrl = Server.HtmlEncode("http://localhost:8665/MySampleApplication/ActivateAccount.aspx? UserID=" & FetchUserId(emailId) & "&EmailId=" & emailId) msg.Body = "Hi " & txtName.Text.Trim() & "!" & vbLf & "Thanks for showing interest and registring in <a href='http://www.webcodeexpert.com'> webcodeexpert.com<a> " & " Please <a href='" & ActivationUrl & "'>click here to activate</a> your account and enjoy our services. " & vbLf & "Thanks!" msg.IsBodyHtml = True smtp.Credentials = New NetworkCredential("YourGmailEmailId@gmail.com","YourGmailPassword") smtp.Port = 587 smtp.Host = "smtp.gmail.com" smtp.EnableSsl = True smtp.Send(msg)

clear_controls() ScriptManager.RegisterStartupScript(Me, Me.[GetType](), "Message", "alert('Confirm ation Link to activate account has been sent to your email address');", True) Catch ex As Exception ScriptManager.RegisterStartupScript(Me, Me.[GetType](), "Message", "alert('Error occured : " & ex.Message.ToString() & "');", True) Return Finally ActivationUrl = String.Empty emailId = String.Empty con.Close() cmd.Dispose() End Try End Sub Private Function FetchUserId(emailId As String) As String Dim cmd As New SqlCommand() cmd = New SqlCommand("SELECT UserId FROM Tb_Registration WHERE EmailId=@EmailId", con) cmd.Parameters.AddWithValue("@EmailId", emailId) If con.State = ConnectionState.Closed Then con.Open() End If Dim UserID As String = Convert.ToString(cmd.ExecuteScalar()) con.Close() cmd.Dispose() Return UserID End Function

Private Sub clear_controls() txtName.Text = String.Empty txtEmailId.Text = String.Empty txtAddress.Text = String.Empty txtContactNo.Text = String.Empty txtName.Focus() End Sub Add a new page ActivateAccount.aspx. This page will be opened when new registered user click on the activate account link in his email. On the page load it will check email id and user id from the query string and then update the "Is_Approved" column to 1 i.e. True. Then you can redirect him to your login page to log in. In the code behind file (ActivateAccount.aspx.vb) and write the code on the page load event as: Imports System.Data Imports System.Data.SqlClient Imports System.Configuration Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load If Not Page.IsPostBack Then ActivateMyAccount() End If End Sub Private Sub ActivateMyAccount() Dim con As New SqlConnection() Dim cmd As New SqlCommand() Try con = NewSqlConnection(ConfigurationManager.ConnectionStrings("conStr").ConnectionString) If (Not String.IsNullOrEmpty(Request.QueryString("UserID"))) And (NotString.IsNul

lOrEmpty(Request.QueryString("EmailId"))) Then 'approve account by setting Is_Approved to 1 i.e. True in the sql server table cmd = New SqlCommand("UPDATE Tb_Registration SET Is_Approved=1 WHERE UserID=@UserID AND EmailId=@EmailId", con) cmd.Parameters.AddWithValue("@UserID", Request.QueryString("UserID")) cmd.Parameters.AddWithValue("@EmailId", Request.QueryString("EmailId")) If con.State = ConnectionState.Closed Then con.Open() End If cmd.ExecuteNonQuery() Response.Write("You account has been activated. You can <a href='Login.aspx'>Login</a> now! ") End If Catch ex As Exception ScriptManager.RegisterStartupScript(Me, Me.[GetType](), "Message", "alert('Error occured : " & ex.Message.ToString() & "');", True) Return Finally con.Close() cmd.Dispose() End Try End Sub Now over to you: "If you like my work; you can appreciate by leaving your comments, hitting Facebook like button, following on Google+, Twitter, Linked in and Pinterest, stumbling my posts on stumble upon and subscribing for receiving free updates directly to your inbox . Stay tuned and stay connected for more technical updates." 2 of 2 Introduction: In this article i am going to explain How to implement remember me next

time checkbox option along with username and password in the Log in form in asp.net using both C# and VB.net language. Username and password will be stored in the cookie . Description: The benefits of implementing remember me option is that user needs not to enter the username and password each time to log in, if he wish. This option will maintain the credentials i.e. username and password for the user when he visit the website next time.

In previous related article i explained How to create Login page/form and check username,password in asp.net using sql server database and Create registration form and send confirmation email to activate account to new registered users and Create Change password form/page in asp.net using Sql server and Encrypt and decrypt username,password and store in Sql Server database and Create contact us form and Recover and reset the forgot password using activation link in email id and Check login in asp.net by passing parameter to stored procedure in sql server . The process is as follows: When user enter username and password and press the login button, the code will first verify the credentials from the Sql server database. If verified then it will further check whether the "remember me next time" checkbox is checked or not. If checked then the username and password will be stored in the cookie for 30 days otherwise it will destroy the cookie by setting the cookie's expiration date to past date. E.g. one day in the past. On page load event we check for the existence of cookie. If exists, username and password will be fetched from the cookie and filled in corresponding TextBox. Implementation: Let's create a sample website to understand the concept. In the <form> tag of the design page (.aspx) place two TextBox controls, a CheckBox and a Button control.

Source Code: <div>

<fieldset style="width:320px;"> <legend>Login with remember me option in asp.net</legend> <table> <tr> <td>UserName : *</td><td> <asp:TextBox ID="txtUserName" placeholder="User Name" Width="180px" runat="server"></asp:TextBox><br /> <asp:RequiredFieldValidator ID="rfvUserName" runat="server" ControlToValidate="txtUserName" Display="Dynamic" ErrorMessage="Please enter User Name" ForeColor="Red" SetFocusOnError="True"></asp:RequiredFieldValidator> </td> </tr> <tr> <td>Password : *</td><td> <asp:TextBox ID="txtPwd" placeholder="Password" TextMode="Password" Width="18 0px" runat="server"></asp:TextBox><br /> <asp:RequiredFieldValidator ID="rfvPwd" runat="server" ControlToValidate="txtPwd" Display="Dynamic" ErrorMessage="Please enter Password" ForeColor="Red" SetFocusOnError="True"></asp:RequiredFieldValidator> </td>

</tr> <tr> <td></td><td> <asp:Button ID="btnLogin" runat="server" Text="Login" onclick="btnLogin_Click" /> <asp:CheckBox ID="chkRemember" Text="Remember me next time" runat="server" /> </td> </tr> </table> </fieldset> </div> Note: I have also validated the username and password using RequiredFieldValidator validation control so that they can't be left blank. Create a database in Sql server e.g. "MyDataBase" and in this database create a table with the columns and data type as shown below and name it "Tb_Login".

Column Id UserName Password

Data Type Int (Primary Key. So set Is Identity=True varchar(100) varchar(100)

Also create a Stored procedure to authenticate the login attempt.

CREATE PROCEDURE CheckLogin_sp @UserName varchar(100), @Pwd AS BEGIN SELECT UserName,[Password] from Tb_Login where UserName COLLATE Latin1_general_CS_AS=@UserName and [Password] COLLATE Latin1_general_CS_AS=@Pwd END Note: In this stored procedure i have also used the COLLATE Latin1_general_CS_AS to check for the exact username and password match because it is used to make the Sql queries case sensitive. e.g. if the username is admin and password is demo then if user enters Admin in username or Demo in password field then it will not match and it the log in attempt will get failed. In the web.config file create the connection string to connect the asp.net website with the Sql server database as: varchar(100)

<connectionStrings> <add name="conStr" connectionString="Data Source=lalit;Initial Catalog=MyDataBase;Integrated Security=True"/> </connectionStrings> Note: Replace the Data Source and Initial catalog (i.e. Database name) as per your application.

C#.Net Code to implement remember me checkbox option in login form In the code behind file (.aspx.cs) write the code as:.

First include the following required namespaces and write the code as: using System.Data; using System.Data.SqlClient; using System.Configuration; protected void btnLogin_Click(object sender, EventArgs e) { SqlConnection con=new SqlConnection(ConfigurationManager.ConnectionStrings["conS tr"].ConnectionString); SqlDataAdapter adp = new SqlDataAdapter(); try { adp = new SqlDataAdapter("CheckLogin_sp", con); adp.SelectCommand.Parameters.AddWithValue("@UserName", txtUserName.Text.Trim()); adp.SelectCommand.Parameters.AddWithValue("@Pwd", txtPwd.Text.Trim()); adp.SelectCommand.CommandType = CommandType.StoredProcedure; if (con.State == ConnectionState.Closed) {

con.Open(); } SqlDataReader dr = adp.SelectCommand.ExecuteReader(); if (dr.HasRows) { if (chkRemember.Checked) { dr.Read(); Response.Cookies["UserName"].Value = txtUserName.Text.Trim(); Response.Cookies["Pwd"].Value = txtPwd.Text.Trim(); Response.Cookies["UserName"].Expires = DateTime.Now.AddDays(30); Response.Cookies["Pwd"].Expires = DateTime.Now.AddDays(30); } else { Response.Cookies["UserName"].Expires = DateTime.Now.AddDays(-1); Response.Cookies["Pwd"].Expires = DateTime.Now.AddDays(-1); } ScriptManager.RegisterStartupScript(this, this.GetType(), "Message", "alert('Login Successful');", true);

} else { ScriptManager.RegisterStartupScript(this, this.GetType(), "Message", "alert('Invalid UserName or Password');", true); } } catch (Exception ex) { ScriptManager.RegisterStartupScript(this, this.GetType(), "Message", "alert('Error occurred : " + ex.Message.ToString() + "');", true); } finally { con.Close(); adp.Dispose(); } } protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack)

{ if (Request.Cookies["UserName"] != null && Request.Cookies["Pwd"] != null) { txtUserName.Text = Request.Cookies["UserName"].Value; txtPwd.Attributes.Add("value", Request.Cookies["Pwd"].Value); chkRemember.Checked = true; } } } VB.Net Code to implement remember me checkbox option in login form In the code behind file (.aspx.vb) write the code as:

First import the following required namespaces and write the code as: Imports System.Data Imports System.Data.SqlClient Imports System.Configuration Protected Sub btnLogin_Click(sender As Object, e As System.EventArgs) Handles btnLogin.Click Dim con As New SqlConnection(ConfigurationManager.ConnectionStrings("conStr").Co nnectionString) Dim adp As New SqlDataAdapter()

Try adp = New SqlDataAdapter("CheckLogin_sp", con) adp.SelectCommand.Parameters.AddWithValue("@UserName", txtUserName.Text.Trim()) adp.SelectCommand.Parameters.AddWithValue("@Pwd", txtPwd.Text.Trim()) adp.SelectCommand.CommandType = CommandType.StoredProcedure If con.State = ConnectionState.Closed Then con.Open() End If Dim dr As SqlDataReader = adp.SelectCommand.ExecuteReader() If dr.HasRows Then If chkRemember.Checked Then dr.Read() Response.Cookies("UserName").Value = txtUserName.Text.Trim() Response.Cookies("Pwd").Value = txtPwd.Text.Trim() Response.Cookies("UserName").Expires = DateTime.Now.AddDays(30) Response.Cookies("Pwd").Expires = DateTime.Now.AddDays(30) Else Response.Cookies("UserName").Expires = DateTime.Now.AddDays(-1) Response.Cookies("Pwd").Expires = DateTime.Now.AddDays(-1)

End If ScriptManager.RegisterStartupScript(Me, Me.[GetType](), "Message", "alert('Log in Successful');", True) Else ScriptManager.RegisterStartupScript(Me, Me.[GetType](), "Message", "alert('Invali d UserName or Password');", True) End If Catch ex As Exception ScriptManager.RegisterStartupScript(Me, Me.[GetType](), "Message", "alert('Error occurred : " & ex.Message.ToString() & "');", True) Finally con.Close() adp.Dispose() End Try End Sub

Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load If Not IsPostBack Then If Request.Cookies("UserName") IsNot Nothing AndAlso Request.Cookies("Pwd") Is Not Nothing Then txtUserName.Text = Request.Cookies("UserName").Value txtPwd.Attributes.Add("value", Request.Cookies("Pwd").Value)

chkRemember.Checked = True End If End If

End Sub Now over to you: "If you like my work; you can appreciate by leaving your comments, hitting Facebook like button, following on Google+, Twitter, Linked in and Pinterest, stumbling my posts on stumble upon and subscribing for receiving free updates directly to your inbox . Stay tuned and stay connected for more technical updates."

How to delete multiple selected records/items based on CheckBox in GridView in asp.net


Introduction: In this article I am going to explain with example How to bind, delete items and delete multiple selected items/ records/ rows from Grid View in asp.net using both C# and VB.Net languages.

Click on the image to enlarge

Description: Basically you will learn the following through this article. How to bind GridView from Sql server database table. How to delete items/records/rows from grid view. How to show Checkbox with each row/record in GridView How to delete multiple records from GridView by selecting multiple items using CheckBox in grid view. How to implement the Confirmation before Deleting gridview records How to implement Paging in GridView In previous article i explained How to Bind,Save,Edit,Update,Cancel,Delete,Paging

example in GridView and WCF Service to bind,insert,edit,update,delete from sql server database in asp.net and Send email to multiple users based on CheckBox selection inside GridView andGet CheckBoxList selected items in comma separated format andBind,upload,download,delete image files from the GridView and Display Serial/Row Number automatically in GridView Implementation: Lets create a sample web application to understand the concept practically.

Source Code:
In the design page (.aspx) place GridView control and set it as: <div> <fieldset style="width:415px;"> <legend>Bind,Delete,Multiple delete example in gridview</legend> <asp:GridView ID="grdEmp" runat="server" AllowSorting="True" ShowFooter="tr ue" DataKeyNames="Emp_Id" CssClass="rowHover" RowStyle-CssClass="rowHov er" AutoGenerateColumns="False" EmptyDataText="No records found" AllowPaging="True" onrowdeleting="grdEmp_RowDeleting" onpageindexchanging="grdEmp_PageIndexChanging" PageSize="10" CellPadding="4" ForeColor="#333333" GridLines="None"> <AlternatingRowStyle BackColor="White" ForeColor="#284775" /> <Columns> <asp:BoundField HeaderText="Emp Name" DataField="EmpName" /> <asp:BoundField HeaderText="Age" DataField="Age" /> <asp:BoundField HeaderText="Salary" DataField="Salary" /> <asp:BoundField HeaderText="Address" DataField="Address" /> <asp:TemplateField HeaderText="Delete" HeaderStyle-HorizontalAlign="Center "ItemStyle-HorizontalAlign="Center"> <ItemTemplate> <asp:ImageButton ID="imgDelete" runat="server" CommandName="Delet

e" ImageUrl="~/Images/Delete.png" OnClientClick="return confirm('Are you sure you want to delete selected record ?')" ToolTip="Delete"/> </ItemTemplate> <HeaderStyle HorizontalAlign="Center" /> <ItemStyle HorizontalAlign="Center" /> </asp:TemplateField> <asp:TemplateField HeaderText="Multiple Delete" HeaderStyle-HorizontalAlign="Center" ItemStyle-HorizontalAlign="Center"> <ItemTemplate> <asp:CheckBox ID="chkDel" runat="server" /> </ItemTemplate> <FooterTemplate> <asp:Button ID="btnDelete" runat="server" Text="Multiple Delete" OnClientClick="return confirm('Are you sure you want to delete selected records?')" onclick="btnDelete_Click" /> </FooterTemplate> <HeaderStyle HorizontalAlign="Center" /> <ItemStyle HorizontalAlign="Center" /> </asp:TemplateField> </Columns> <EditRowStyle BackColor="#999999" /> <FooterStyle BackColor="#ffffff" Font-Bold="True" ForeColor="White" /> <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" /> <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Cent er" /> <RowStyle CssClass="rowHover" BackColor="#F7F6F3" ForeColor="#333333"></R owStyle> <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#33 3333"/> <SortedAscendingCellStyle BackColor="#E9E7E2" /> <SortedAscendingHeaderStyle BackColor="#506C8C" /> <SortedDescendingCellStyle BackColor="#FFFDF8" /> <SortedDescendingHeaderStyle BackColor="#6F8DAE" /> <EmptyDataRowStyle Width = "410px" ForeColor="Red" Font-Bold="true"

HorizontalAlign = "Center"/> </asp:GridView> </fieldset> </div> Note: Create a folder in the root directory and name it Images and place the delete image icon in this folder. You can search on google for the term delete png icons.

Now Create a Database in Sql server e.g. Emp_DB and create a Table with the columns and the Data type as shown below and name it Emp_Tb.

Column Name Emp_Id

Data Type

Int( Primary Key. So set Is Identity=True) EmpName varchar(100) Age int Salary int Address varchar(500)
Create a stored procedure to fetch the employee records and bind gridview CREATE PROCEDURE BindEmpGrid_Sp AS BEGIN SELECT * FROM Emp_Tb END Create a stored procedure to delete the employee records CREATE PROCEDURE DeleteEmpRecord_Sp @EmpId INT AS BEGIN DELETE FROM Emp_Tb WHERE Emp_Id=@EmpId END

In the web.con fig file create the connection string to connect the asp.net web application with the Sql server database. <connectionStrings>

<add name="con" connectionString="Data Source=Lalit;Initial Catalog=Emp_DB;Integrated Security=True"/> </connectionStrings> Note: Replace the Data Source and Initial catalog (i.e. Database Name) as per your application.

C#.Net Code to bind,delete and multiple deletion using checkbox from gridview
In the code behind file (.aspx.cs) write the code as: First include the required namespaces and then write the below mentioned code: using System.Data; using System.Data.SqlClient; using System.Configuration; SqlConnection con = newSqlConnection(ConfigurationManager.ConnectionStrings["con"].ConnectionStri ng); protected void Page_Load(object sender, EventArgs e) { if (con.State == ConnectionState.Closed) { con.Open(); } if (!Page.IsPostBack) { BindEmpGrid(); } } #region "Bind GridView" private void BindEmpGrid() { SqlDataAdapter adp = new SqlDataAdapter(); DataTable dt = new DataTable(); try {

adp = new SqlDataAdapter("BindEmpGrid_Sp", con); adp.Fill(dt); if (dt.Rows.Count > 0) { grdEmp.DataSource = dt; grdEmp.DataBind(); } else { grdEmp.DataSource = null; grdEmp.DataBind(); } } catch (Exception ex) { ScriptManager.RegisterStartupScript(this, this.GetType(), "Message", "alert('Err or occured : " + ex.Message.ToString() + "');", true); } finally { dt.Clear(); dt.Dispose(); adp.Dispose(); con.Close(); } } #endregion #region "GridView Paging" protected void grdEmp_PageIndexChanging(object sender, GridViewPageEventArg s e) { grdEmp.PageIndex = e.NewPageIndex; BindEmpGrid(); } #endregion #region "Deletion in gridview"

protected void grdEmp_RowDeleting(object sender, GridViewDeleteEventArgs e) { SqlCommand cmd = new SqlCommand(); try { //get EmpId from DatakeyNames from gridview int empId = Convert.ToInt32(grdEmp.DataKeys[e.RowIndex].Value); cmd = new SqlCommand("DeleteEmpRecord_Sp", con); cmd.Parameters.Add("@EmpId", SqlDbType.Int).Value = empId; cmd.CommandType = CommandType.StoredProcedure; cmd.ExecuteNonQuery(); BindEmpGrid(); ScriptManager.RegisterClientScriptBlock(Page, Page.GetType(),Guid.NewGuid().ToString(), "alert('Record has been deleted successfully');", true); } catch (Exception ex) { ScriptManager.RegisterStartupScript(this, this.GetType(), "Message", "alert('Err or occured : " + ex.Message.ToString() + "');", true); } finally { cmd.Dispose(); con.Close(); } } #endregion #region "To delete multiple record" protected void btnDelete_Click(object sender, EventArgs e) { SqlCommand cmd = new SqlCommand(); try { //Loop through all the rows in gridview foreach (GridViewRow grv in grdEmp.Rows) {

//Finiding checkbox control in gridview for particular row CheckBox chk = (CheckBox)grv.FindControl("chkDel"); if (chk.Checked) { //get EmpId from DatakeyNames from gridview int empid = Convert.ToInt32(grdEmp.DataKeys[grv.RowIndex].Value); cmd = new SqlCommand("DeleteEmpRecord_Sp", con); cmd.Parameters.Add("@EmpId", SqlDbType.Int).Value = empid; cmd.CommandType = CommandType.StoredProcedure; cmd.ExecuteNonQuery(); } } grdEmp.EditIndex = -1; BindEmpGrid(); ScriptManager.RegisterClientScriptBlock(Page, Page.GetType(),Guid.NewGuid().ToString(), "alert('Selected Records has been deleted successfully');", true); } catch (Exception ex) { ScriptManager.RegisterStartupScript(this, this.GetType(), "Message", "alert('Err or occured : " + ex.Message.ToString() + "');", true); } finally { cmd.Dispose(); con.Close(); } } #endregion

VB.Net Code to bind,delete and multiple deletion using checkbox from gridview
Design the page as shown above in the source code but delete theonrowdeleting="grdEmp_RowDeleting" onpageindexchanging="grdEmp_Pa geIndexChanging" from the grid view source code.

In the code behind file (.aspx.vb) write the code as: First include the required namespaces and then write the below mentioned code Imports System.Data Imports System.Data.SqlClient Imports System.Configuration Dim con As NewSqlConnection(ConfigurationManager.ConnectionStrings("con").Con nectionString) Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load If con.State = ConnectionState.Closed Then con.Open() End If If Not Page.IsPostBack Then BindEmpGrid() End If End Sub #Region "Bind GridView" Private Sub BindEmpGrid() Dim adp As New SqlDataAdapter() Dim dt As New DataTable() Try adp = New SqlDataAdapter("BindEmpGrid_Sp", con) adp.Fill(dt) If dt.Rows.Count > 0 Then grdEmp.DataSource = dt grdEmp.DataBind() Else grdEmp.DataSource = Nothing grdEmp.DataBind() End If Catch ex As Exception ScriptManager.RegisterStartupScript(Me, Me.[GetType](), "Message", "alert('Er ror occured : " & ex.Message.ToString() & "');", True) Finally dt.Clear()

dt.Dispose() adp.Dispose() End Try End Sub #End Region #Region "GridView paging" Protected Sub grdEmp_PageIndexChanging(sender As Object, e AsSystem.Web.UI.WebControls.GridViewPageEventArgs) Handles grdEmp.PageInde xChanging grdEmp.PageIndex = e.NewPageIndex BindEmpGrid() End Sub #End Region Protected Sub grdEmp_RowDeleting(sender As Object, e AsSystem.Web.UI.WebControls.GridViewDeleteEventArgs) Handles grdEmp.RowDel eting Dim cmd As New SqlCommand() Try 'get EmpId from DatakeyNames from gridview Dim empId As Integer = Convert.ToInt32(grdEmp.DataKeys(e.RowIndex).Value ) cmd = New SqlCommand("DeleteEmpRecord_Sp", con) cmd.Parameters.Add("@EmpId", SqlDbType.Int).Value = empId cmd.CommandType = CommandType.StoredProcedure cmd.ExecuteNonQuery() BindEmpGrid() ScriptManager.RegisterClientScriptBlock(Page, Page.[GetType] (),Guid.NewGuid().ToString(), "alert('Record has been deleted successfully');", True) Catch ex As Exception ScriptManager.RegisterStartupScript(Me, Me.[GetType](), "Message", "alert('Er ror occured : " & ex.Message.ToString() & "');", True) Finally cmd.Dispose() con.Close() End Try

End Sub Protected Sub btnDelete_Click(sender As Object, e As System.EventArgs) Dim cmd As New SqlCommand() Try 'Loop through all the rows in gridview For Each grv As GridViewRow In grdEmp.Rows 'Finiding checkbox control in gridview for particular row Dim chk As CheckBox = DirectCast(grv.FindControl("chkDel"), CheckBox) If chk.Checked Then 'get EmpId from DatakeyNames from gridview Dim empid As Integer = Convert.ToInt32(grdEmp.DataKeys(grv.RowIndex). Value) cmd = New SqlCommand("DeleteEmpRecord_Sp", con) cmd.Parameters.Add("@EmpId", SqlDbType.Int).Value = empid cmd.CommandType = CommandType.StoredProcedure cmd.ExecuteNonQuery() End If Next grdEmp.EditIndex = -1 BindEmpGrid() ScriptManager.RegisterClientScriptBlock(Page, Page.[GetType] (),Guid.NewGuid().ToString(), "alert('Selected Records has been deleted successfully');", True) Catch ex As Exception ScriptManager.RegisterStartupScript(Me, Me.[GetType](), "Message", "alert('Er ror occured : " & ex.Message.ToString() & "');", True) Finally cmd.Dispose() con.Close() End Try End Sub

How to bind and implement search gridview records in asp.net | Use of If Else If in Sql server
Introduction: In this article I am going to explain with example How to Bind

GridView from Sql server database table and implement search /filter functionality in the grid view in asp.net using both C#.Net and VB.Net languages.

Click on the image to view enlarged demo

Description: You will learn the following through this article: How to Bind gridview from sql server database table using stored procedure How to implement the search/filter feature in grid view to search the records based on selected criteria. In this example i have implemented the functionality to filter the records by Emp Name, Salary and City. How to use nested If Else If in stored procedure in Sql server How to use CASE in stored procedure in Sql server In previous articles i explained How to Bind,Save,Edit,Update,Cancel,Delete,Paging example in GridView and WCF Service to bind,insert,edit,update,delete from sql server database in asp.net and Delete multiple selected records/items based on CheckBox in GridView and Bind,upload,download,delete image files from the GridView and Display Serial/Row Number automatically in GridView and Highlight gridview row on mouse over using CSS in asp.net and Bind empty GridView with header and custom message Implementation: Lets create sample asp.net website to see it in action. First of all create a Database in Sql server e.g. Emp_DB and in this database create a table with the columns and data type as shown below:

Column Name Emp_Id

Data Type

Int(Primary Key. So set Is Identity=True) EmpName varchar(100) Age int

Salary City Address

int varchar(100) varchar(500)

Now create a Stored Procedure to get/fetch the employee records based on search criteria. Note: In have mentioned two stored procedure for the same purpose. You can use any of the two. The first one which is simple, demonstrates the use of IF.. ELSE IF..ELSE (Nested Else if) to execute different queries based on conditions and the second one demonstrates the use of Case statement for the same purpose. CREATE PROCEDURE SearchEmpRecords_Sp @SearchBy @SearchVal AS BEGIN IF @SearchBy = 'Emp Name' BEGIN SELECT * FROM Emp_Tb WHERE EmpName like @SearchVal + '%' END ELSE IF @SearchBy = 'City' BEGIN SELECT * FROM Emp_Tb WHERE City like @SearchVal + '%' END ELSE IF @SearchBy = 'Salary' BEGIN SELECT * FROM Emp_Tb WHERE Salary = @SearchVal END ELSE BEGIN SELECT * FROM Emp_Tb END END ---------------------------------------------------------------------------------------------------------CREATE PROCEDURE SearchEmpRecords_Sp @SearchBy varchar(50), varchar(50), varchar(50)

@SearchVal AS BEGIN

varchar(50)

DECLARE @sql NVARCHAR(1000) SELECT @sql=CASE @SearchBy WHEN 'Emp Name' THEN 'SELECT * FROM Emp_Tb WHERE EmpName LIKE '''+ @SearchVal+'%''' WHEN 'City' '''+ @SearchVal +'%''' WHEN 'Salary' THEN 'SELECT * FROM Emp_Tb WHERE Salary = ' + @SearchVal + '' ELSE '(SELECT * FROM Emp_Tb)' END END EXECUTE sp_executesql @sql THEN 'SELECT * FROM Emp_Tb WHERE City LIKE

In the web.config file create the connection string to connect the asp.net web application with the Sql server database as: <connectionStrings> <add name="con" connectionString="Data Source=Lalit;Initial Catalog=Emp_DB;Integrated Security=True"/> </connectionStrings> Note: Replace the Data source and Ini tial Catalog (i.e. Database Name) as per your application.

Source Code:
In the design page(.aspx) design the page as: <div> <fieldset style="width:415px;"> <legend>Bind and Search records example in gridview</legend> <table>

<tr><td>Search By: <asp:DropDownList ID="ddlSearchBy" runat="server" AutoPostBack="True" onselectedindexchanged="ddlSearchBy_SelectedIndexChanged"> <asp:ListItem Text="All"></asp:ListItem> <asp:ListItem Text="Emp Name"></asp:ListItem> <asp:ListItem Text="Salary"></asp:ListItem> <asp:ListItem Text="City"></asp:ListItem> </asp:DropDownList> </td><td> <asp:TextBox ID="txtSearch" runat="server"></asp:TextBox> </td><td> <asp:Button ID="btnSearch" runat="server" Text="Search" onclick="btnSearch_Click" /> </td></tr> </table> <asp:GridView ID="grdEmp" runat="server" AllowSorting="True" EmptyDataText= "No records found" CssClass="rowHover" RowStyle-CssClass="rowHover" ShowHeader="true" AutoGenerateColumns="False" AllowPaging="True" onpageindexchanging="grdEmp_PageIndexChanging" PageSize="5" CellPadding="4" ForeColor="#333333" GridLines="None" Width="100%"> <AlternatingRowStyle BackColor="White" ForeColor="#284775" /> <Columns> <asp:BoundField HeaderText="Emp Name" DataField="EmpName" ItemStyle-HorizontalAlign="Center" /> <asp:BoundField HeaderText="Age" DataField="Age" ItemStyle-HorizontalAlign ="Center" /> <asp:BoundField HeaderText="Salary" DataField="Salary" ItemStyle-Horizontal Align="Center" /> <asp:BoundField HeaderText="City" DataField="City" ItemStyle-HorizontalAlign ="Center" /> <asp:BoundField HeaderText="Address" DataField="Address" ItemStyle-Horizon talAlign="Center" /> </Columns>

<EditRowStyle BackColor="#999999" /> <FooterStyle BackColor="#ffffff" Font-Bold="True" ForeColor="White" /> <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" /> <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Cent er" /> <RowStyle CssClass="rowHover" BackColor="#F7F6F3" ForeColor="#333333"></R owStyle> <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#33 3333"/> <SortedAscendingCellStyle BackColor="#E9E7E2" /> <SortedAscendingHeaderStyle BackColor="#506C8C" /> <SortedDescendingCellStyle BackColor="#FFFDF8" /> <SortedDescendingHeaderStyle BackColor="#6F8DAE" /> <EmptyDataRowStyle Width = "550px" ForeColor="Red" Font-Bold="true" HorizontalAlign = "Center"/> </asp:GridView> </fieldset> </div>

C#.Net Code to bind and implement searching in GridView


In the code behind file (.aspx.cs) write the code as: First include the following required namespaces using System.Data; using System.Data.SqlClient; using System.Configuration; SqlConnection con = newSqlConnection(ConfigurationManager.ConnectionStrings["con"].ConnectionStri ng); protected void Page_Load(object sender, EventArgs e) { if (con.State == ConnectionState.Closed) { con.Open(); } if (!Page.IsPostBack)

{ BindEmpGrid(); txtSearch.Enabled = false; } } private void BindEmpGrid() { SqlDataAdapter adp = new SqlDataAdapter(); DataTable dt = new DataTable(); try { adp = new SqlDataAdapter("BindEmpGrid_Sp", con); adp.Fill(dt); if (dt.Rows.Count > 0) { grdEmp.DataSource = dt; grdEmp.DataBind(); } else { grdEmp.DataSource = null; grdEmp.DataBind(); } } catch (Exception ex) { ScriptManager.RegisterStartupScript(this, this.GetType(), "Message", "alert('Err or occured : " + ex.Message.ToString() + "');", true); } finally { dt.Clear(); dt.Dispose(); adp.Dispose(); con.Close(); } }

protected void ddlSearchBy_SelectedIndexChanged(object sender, EventArgs e) { if (ddlSearchBy.SelectedItem.Text == "All") { txtSearch.Text = string.Empty; txtSearch.Enabled = false; } else { txtSearch.Enabled = true; txtSearch.Text = string.Empty; txtSearch.Focus(); } } protected void btnSearch_Click(object sender, EventArgs e) { DataTable dt = new DataTable(); SqlCommand cmd = new SqlCommand(); SqlDataAdapter adp=new SqlDataAdapter(); try { if (ddlSearchBy.SelectedItem.Text == "Emp Name") { getEmpRecords(ddlSearchBy.SelectedItem.Text, txtSearch.Text.Trim()); } else if (ddlSearchBy.SelectedItem.Text == "City") { getEmpRecords(ddlSearchBy.SelectedItem.Text, txtSearch.Text.Trim()); } else if (ddlSearchBy.SelectedItem.Text == "Salary") { getEmpRecords(ddlSearchBy.SelectedItem.Text, txtSearch.Text.Trim()); }

else { getEmpRecords(ddlSearchBy.SelectedItem.Text, txtSearch.Text.Trim()); } } catch (Exception ex) { ScriptManager.RegisterStartupScript(this, this.GetType(), "Message", "alert('Err or occured : " + ex.Message.ToString() + "');", true); } finally { dt.Clear(); dt.Dispose(); cmd.Dispose(); con.Close(); } } private void getEmpRecords(string searchBy, string searchVal) { DataTable dt = new DataTable(); SqlCommand cmd = new SqlCommand(); SqlDataAdapter adp = new SqlDataAdapter(); try { cmd = new SqlCommand("SearchEmpRecords1_Sp", con); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@SearchBy", searchBy); cmd.Parameters.AddWithValue("@SearchVal", searchVal); adp.SelectCommand = cmd; adp.Fill(dt); if (dt.Rows.Count > 0) { grdEmp.DataSource = dt; grdEmp.DataBind(); }

else { grdEmp.DataSource = dt; grdEmp.DataBind(); } } catch (Exception ex) { ScriptManager.RegisterStartupScript(this, this.GetType(), "Message", "alert('Err or occured : " + ex.Message.ToString() + "');", true); } finally { dt.Clear(); dt.Dispose(); cmd.Dispose(); con.Close(); } } protected void grdEmp_PageIndexChanging(object sender, GridViewPageEventArg s e) { grdEmp.PageIndex = e.NewPageIndex; BindEmpGrid(); }

VB.Net Code

to bind and implement searching in GridView

In the design page(.aspx) design the page as shown above in Source Code section but replace the line <asp:DropDownList ID="ddlSearchBy" runat="server" AutoPostBack="True" onselectedindexchanged="ddlSearchBy_SelectedIndexChanged"> with <asp:DropDownList ID="ddlSearchBy" runat="server" AutoPostBack="True" > Similarly replace the line

<asp:Button ID="btnSearch" runat="server" Text="Search" onclick="btnSearch_Click" /> with <asp:Button ID="btnSearch" runat="server" Text="Search" /> and also remove the onpageindexchanging="grdEmp_PageIndexChanging" from the Grid View source . In the code behind file (.aspx.vb) write the code as: First import the following namespaces Imports System.Data Imports System.Data.SqlClient Imports System.Configuration Dim con As NewSqlConnection(ConfigurationManager.ConnectionStrings("con").Con nectionString) Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load If con.State = ConnectionState.Closed Then con.Open() End If If Not Page.IsPostBack Then BindEmpGrid() txtSearch.Enabled = False End If End Sub Private Sub BindEmpGrid() Dim adp As New SqlDataAdapter() Dim dt As New DataTable() Try adp = New SqlDataAdapter("BindEmpGrid_Sp", con) adp.Fill(dt) If dt.Rows.Count > 0 Then grdEmp.DataSource = dt grdEmp.DataBind() Else grdEmp.DataSource = Nothing

grdEmp.DataBind() End If Catch ex As Exception ScriptManager.RegisterStartupScript(Me, Me.[GetType](), "Message", "alert('Er ror occured : " & ex.Message.ToString() & "');", True) Finally dt.Clear() dt.Dispose() adp.Dispose() con.Close() End Try End Sub Protected Sub ddlSearchBy_SelectedIndexChanged(sender As Object, e AsSystem.EventArgs) Handles ddlSearchBy.SelectedIndexChanged If ddlSearchBy.SelectedItem.Text = "All" Then txtSearch.Text = String.Empty txtSearch.Enabled = False Else txtSearch.Enabled = True txtSearch.Text = String.Empty txtSearch.Focus() End If End Sub Protected Sub btnSearch_Click(sender As Object, e As System.EventArgs) HandlesbtnSearch.Click Dim dt As New DataTable() Dim cmd As New SqlCommand() Dim adp As New SqlDataAdapter() Try If ddlSearchBy.SelectedItem.Text = "Emp Name" Then getEmpRecords(ddlSearchBy.SelectedItem.Text, txtSearch.Text.Trim()) ElseIf ddlSearchBy.SelectedItem.Text = "City" Then getEmpRecords(ddlSearchBy.SelectedItem.Text, txtSearch.Text.Trim()) ElseIf ddlSearchBy.SelectedItem.Text = "Salary" Then getEmpRecords(ddlSearchBy.SelectedItem.Text, txtSearch.Text.Trim()) Else

getEmpRecords(ddlSearchBy.SelectedItem.Text, txtSearch.Text.Trim()) End If Catch ex As Exception ScriptManager.RegisterStartupScript(Me, Me.[GetType](), "Message", "alert('Er ror occured : " & ex.Message.ToString() & "');", True) Finally dt.Clear() dt.Dispose() cmd.Dispose() con.Close() End Try End Sub Private Sub getEmpRecords(searchBy As String, searchVal As String) Dim dt As New DataTable() Dim cmd As New SqlCommand() Dim adp As New SqlDataAdapter() Try cmd = New SqlCommand("SearchEmpRecords1_Sp", con) cmd.CommandType = CommandType.StoredProcedure cmd.Parameters.AddWithValue("@SearchBy", searchBy) cmd.Parameters.AddWithValue("@SearchVal", searchVal) adp.SelectCommand = cmd adp.Fill(dt) If dt.Rows.Count > 0 Then grdEmp.DataSource = dt grdEmp.DataBind() Else grdEmp.DataSource = dt grdEmp.DataBind() End If Catch ex As Exception ScriptManager.RegisterStartupScript(Me, Me.[GetType](), "Message", "alert('Er ror occured : " & ex.Message.ToString() & "');", True) Finally dt.Clear() dt.Dispose() cmd.Dispose()

con.Close() End Try End Sub Protected Sub grdEmp_PageIndexChanging(sender As Object, e AsSystem.Web.UI.WebControls.GridViewPageEventArgs) Handles grdEmp.PageInde xChanging grdEmp.PageIndex = e.NewPageIndex BindEmpGrid() End Sub