Bind DropdownList from Database in ASP.NET
Bind DropdownList from Database in ASP.NET
NET
Introduction: Here I will explain how to bind or show data in dropdownlist from database in [Link] using C#.net [Link]. Description: In previous posts I explained many articles relating [Link], jQuery, SQL Server, JavaScript. Now I will explain how to bind or show data in dropdownlist from database in [Link] using C#.net and [Link]. 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="[Link] <head runat="server"> <title>how to show data in dropdownlist from database in [Link]</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 [Link]; using [Link]; using [Link]; After add namespaces write the following code in code behind
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")) { [Link](); SqlCommand cmd = new SqlCommand("Select UserId,UserName FROM UserInformation", con); SqlDataAdapter da = new SqlDataAdapter(cmd); DataSet ds = new DataSet(); [Link](ds); [Link] = ds; [Link] = "UserName"; [Link] = "UserId"; [Link](); [Link](0, new ListItem("--Select--", "0")); [Link](); } } [Link] Code
Imports [Link] Imports [Link] Imports [Link] Partial Class VBSample Inherits [Link] Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles [Link] 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") [Link]() Dim cmd As New SqlCommand("Select UserId,UserName FROM UserInformation", con) Dim da As New SqlDataAdapter(cmd) Dim ds As New DataSet() [Link](ds) [Link] = ds [Link] = "UserName" [Link] = "UserId" [Link]() [Link](0, New ListItem("--Select--", "0")) [Link]() End Using End Sub End Class Demo
How to Bind /Load /Fill Countries, States and Cities in the DropDownList fromSql
Server Database in [Link] using C# and [Link] 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 [Link] and How to fill dropdownlist with days, month and year in [Link](C#, VB) and Fill CheckBoxList based on DropDownList selection and Example to Validate DropDownList using jQuery in [Link].
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
Set is identity=yes
Country_Id_P k 1 2
State_Id_p k 1 2 3 4
country_Id_ Fk 1 1 1 2
City_Name varchar(10
State_Id_Fk
0) int
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 [Link] 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 [Link]</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
In the Code behind file (.[Link]) write the code as: First include the following namespaces: using [Link]; using [Link]; using [Link]; Then write the code as: //Creating and initializing connection object. SqlConnection con = newSqlConnection([Link]["conStr"].ConnectionString); protected void Page_Load(object sender, EventArgs e) { //Checking Connection State and opening if closed if ([Link] == [Link]) { [Link](); } if (![Link]) { //Call countries DropDownList on page load event BindContriesDropDownList(); } }
protected void ddlCountry_SelectedIndexChanged(object sender, EventArgs e) { try { int CountryId = Convert.ToInt32([Link]); //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(); [Link](ds); [Link] = ds; [Link] = "State_Name"; [Link] = "State_Id_Pk"; [Link](); [Link](0, new ListItem("--Select--", "0")); //If State is not selected then clear City DropDownList also if ([Link] == "0") { [Link](); [Link](0, new ListItem("--Select--", "0")); } } catch (Exception ex) { //Printing any exception if occcured. [Link]("Error occured: " + [Link]()); } finally { //Close the connection [Link](); } } protected void ddlState_SelectedIndexChanged(object sender, EventArgs e) { try { int StateId = Convert.ToInt32([Link]);
//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(); [Link](ds); [Link] = ds; [Link] = "City_Name"; [Link] = "City_id_pk"; [Link](); [Link](0, new ListItem("--Select--", "0")); } catch (Exception ex) { [Link]("Error occured : " + [Link]()); } finally { [Link](); } } protected void BindContriesDropDownList() { try { SqlDataAdapter adp = new SqlDataAdapter("select * from Tbl_Country", con); DataSet ds = new DataSet(); [Link](ds); [Link] = ds; [Link] = "Country_Name"; [Link] = "Country_Id_Pk"; [Link](); [Link](0, new ListItem("--Select--", "0")); [Link](0, new ListItem("--Select--", "0")); [Link](0, new ListItem("--Select--", "0")); } catch (Exception ex) {
In the Code behind file (.[Link]) write the code as: First import the following namerspaces: Imports [Link]
Imports [Link] Imports [Link] Then write the code as: 'Creating and initializing connection object. Dim con As NewSqlConnection([Link]("conStr").Connectio nString) Protected Sub Page_Load(sender As Object, e As [Link]) Handles [Link] 'Checking Connection State and opening if closed If [Link] = [Link] Then [Link]() End If If Not [Link] Then 'Call countries DropDownList on page load event BindContriesDropDownList() End If End Sub Protected Sub ddlCountry_SelectedIndexChanged(sender As Object, e [Link]) Handles [Link] Try Dim CountryId As Integer = Convert.ToInt32([Link]) '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() [Link](ds) [Link] = ds [Link] = "State_Name" [Link] = "State_Id_Pk" [Link]() [Link](0, New ListItem("--Select--", "0")) 'If State is not selected then clear City DropDownList also If [Link] = "0" Then [Link]() [Link](0, New ListItem("--Select--", "0")) End If
Catch ex As Exception 'Printing any exception if occcured. [Link]("Error occured: " & [Link]()) Finally 'Close the connection [Link]() End Try End Sub Protected Sub ddlState_SelectedIndexChanged(sender As Object, e As [Link])Handles [Link] Try Dim StateId As Integer = Convert.ToInt32([Link]) '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() [Link](ds) [Link] = ds [Link] = "City_Name" [Link] = "City_id_pk" [Link]() [Link](0, New ListItem("--Select--", "0")) Catch ex As Exception [Link]("Error occured : " & [Link]()) Finally [Link]() End Try End Sub Protected Sub BindContriesDropDownList() Try Dim adp As New SqlDataAdapter("select * from Tbl_Country", con) Dim ds As New DataSet() [Link](ds) [Link] = ds [Link] = "Country_Name" [Link] = "Country_Id_Pk"
[Link]() [Link](0, New ListItem("--Select--", "0")) [Link](0, New ListItem("--Select--", "0")) [Link](0, New ListItem("--Select--", "0")) Catch ex As Exception [Link]("Error occured : " & [Link]()) Finally [Link]() 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 Bind /Load /Fill Countries, States and Cities in the DropDownList fromSql
Server Database in [Link] using C# and [Link] 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 [Link] and How to fill dropdownlist with days, month and year in [Link](C#, VB) and Fill CheckBoxList based on DropDownList selection and Example to Validate DropDownList using jQuery in [Link].
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.
Set is identity=yes
Country_Id_ Pk 1 2
Set is identity=yes
State_Id_ pk 1 2 3 4
country_Id _Fk 1 1 1 2
Column Name
Data type
City_Id_Pk
int
Set is identity=yes
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 [Link] 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 [Link]</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
In the Code behind file (.[Link]) write the code as: First include the following namespaces: using [Link]; using [Link]; using [Link]; Then write the code as: //Creating and initializing connection object. SqlConnection con = newSqlConnection([Link]["conStr"].Connection String); protected void Page_Load(object sender, EventArgs e) { //Checking Connection State and opening if closed if ([Link] == [Link]) { [Link](); }
if (![Link]) { //Call countries DropDownList on page load event BindContriesDropDownList(); } } protected void ddlCountry_SelectedIndexChanged(object sender, EventArgs e) { try { int CountryId = Convert.ToInt32([Link]); //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(); [Link](ds); [Link] = ds; [Link] = "State_Name"; [Link] = "State_Id_Pk"; [Link](); [Link](0, new ListItem("--Select--", "0")); //If State is not selected then clear City DropDownList also if ([Link] == "0") { [Link](); [Link](0, new ListItem("--Select--", "0")); } } catch (Exception ex) { //Printing any exception if occcured. [Link]("Error occured: " + [Link]()); } finally { //Close the connection [Link](); }
} protected void ddlState_SelectedIndexChanged(object sender, EventArgs e) { try { int StateId = Convert.ToInt32([Link]); //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(); [Link](ds); [Link] = ds; [Link] = "City_Name"; [Link] = "City_id_pk"; [Link](); [Link](0, new ListItem("--Select--", "0")); } catch (Exception ex) { [Link]("Error occured : " + [Link]()); } finally { [Link](); } } protected void BindContriesDropDownList() { try { SqlDataAdapter adp = new SqlDataAdapter("select * from Tbl_Country", con); DataSet ds = new DataSet(); [Link](ds); [Link] = ds; [Link] = "Country_Name"; [Link] = "Country_Id_Pk"; [Link]();
[Link](0, new ListItem("--Select--", "0")); [Link](0, new ListItem("--Select--", "0")); [Link](0, new ListItem("--Select--", "0")); } catch (Exception ex) { [Link]("Error occured : " + [Link]()); } finally { [Link](); } }
</fieldset>
In the Code behind file (.[Link]) write the code as: First import the following namerspaces: Imports [Link] Imports [Link] Imports [Link] Then write the code as: 'Creating and initializing connection object. Dim con As NewSqlConnection([Link]("conStr"). ConnectionString) Protected Sub Page_Load(sender As Object, e As [Link]) Handles [Link] 'Checking Connection State and opening if closed If [Link] = [Link] Then [Link]() End If If Not [Link] Then 'Call countries DropDownList on page load event BindContriesDropDownList() End If End Sub Protected Sub ddlCountry_SelectedIndexChanged(sender As Object, e [Link]) Handles [Link] Try Dim CountryId As Integer = Convert.ToInt32([Link]) '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() [Link](ds) [Link] = ds [Link] = "State_Name" [Link] = "State_Id_Pk" [Link]()
[Link](0, New ListItem("--Select--", "0")) 'If State is not selected then clear City DropDownList also If [Link] = "0" Then [Link]() [Link](0, New ListItem("--Select--", "0")) End If Catch ex As Exception 'Printing any exception if occcured. [Link]("Error occured: " & [Link]()) Finally 'Close the connection [Link]() End Try End Sub Protected Sub ddlState_SelectedIndexChanged(sender As Object, e As [Link])Handles [Link] Try Dim StateId As Integer = Convert.ToInt32([Link]) '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() [Link](ds) [Link] = ds [Link] = "City_Name" [Link] = "City_id_pk" [Link]() [Link](0, New ListItem("--Select--", "0")) Catch ex As Exception [Link]("Error occured : " & [Link]()) Finally [Link]() End Try End Sub Protected Sub BindContriesDropDownList() Try
Dim adp As New SqlDataAdapter("select * from Tbl_Country", con) Dim ds As New DataSet() [Link](ds) [Link] = ds [Link] = "Country_Name" [Link] = "Country_Id_Pk" [Link]() [Link](0, New ListItem("--Select--", "0")) [Link](0, New ListItem("--Select--", "0")) [Link](0, New ListItem("--Select--", "0")) Catch ex As Exception [Link]("Error occured : " & [Link]()) Finally [Link]() 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 [Link] | 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 [Link] with both C#.Net and [Link] 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 "[Link]" 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 [Link] 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 [Link] file create the connection string to connect your [Link] 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 [Link] 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> </td><td> <asp:Button ID="btnSubmit" runat="server" Text="Submit" onclick="btnSubmit_Click" /></td> </tr> </table> </fieldset> </div> C#.Net Code for [Link] In the code behind file ([Link]) write the code as: using [Link]; using [Link]; using [Link]; using [Link]; using [Link]; using [Link]; SqlConnection con = newSqlConnection([Link]["conStr"].ConnectionString); protected void btnSubmit_Click(object sender, EventArgs e) { MailMessage msg; SqlCommand cmd = new SqlCommand(); string ActivationUrl = [Link]; string emailId = [Link];
try { cmd = new SqlCommand("insert into Tb_Registration (Name,EmailId,Address,ContactNo) values (@Name,@EmailId,@Address,@ContactNo) ", con); [Link]("@Name", [Link]()); [Link]("@EmailId", [Link]()); [Link]("@Address", [Link]()); [Link]("@ContactNo", [Link]()); if ([Link] == [Link]) { [Link](); } [Link](); //Sending activation link in the email msg = new MailMessage(); SmtpClient smtp = new SmtpClient(); emailId = [Link](); //sender email address [Link] = new MailAddress("YourGmailEmailId@[Link]"); //Receiver email address [Link](emailId); [Link] = "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 = [Link]("[Link] UserID=" + FetchUserId(emailId) + "&EmailId=" + emailId);
[Link] = "Hi " + [Link]() + "!\n" + "Thanks for showing interest and registring in <a href='[Link] [Link]<a> " + " Please <a href='" + ActivationUrl + "'>click here to activate</a> your account and enjoy our services. \nThanks!"; [Link] = true; [Link] = new NetworkCredential("YourGmailEmailId@[Link]","YourGmailPassword"); [Link] = 587; [Link] = "[Link]"; [Link] = true; [Link](msg); clear_controls(); [Link](this, [Link](), "Message", "alert('Confirmat ion Link to activate your account has been sent to your email address');", true); } catch (Exception ex) { [Link](this, [Link](), "Message", "alert('Error occured : " + [Link]() + "');", true); return; } finally { ActivationUrl = [Link]; emailId = [Link]; [Link](); [Link]();
} } private string FetchUserId(string emailId) { SqlCommand cmd = new SqlCommand(); cmd = new SqlCommand("SELECT UserId FROM Tb_Registration WHERE EmailId=@EmailId", con); [Link]("@EmailId", emailId); if ([Link] == [Link]) { [Link](); } string UserID = [Link]([Link]()); [Link](); [Link](); return UserID; } private void clear_controls() { [Link] = [Link]; [Link] = [Link]; [Link] = [Link]; [Link] = [Link]; [Link](); } Add a new page and name it [Link]. 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 [Link] page In the code behind file ([Link]) write the code as: using [Link]; using [Link]; using [Link]; protected void Page_Load(object sender, EventArgs e) { if (![Link]) { ActivateMyAccount(); } } private void ActivateMyAccount() { SqlConnection con = new SqlConnection(); SqlCommand cmd = new SqlCommand(); try { con = newSqlConnection([Link]["conStr"].ConnectionString); if (() & (! [Link]([Link]["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); [Link]("@UserID", [Link]["UserID"]); [Link]("@EmailId", [Link]["EmailId"]); if ([Link] == [Link]) { [Link](); } [Link](); [Link]("You account has been activated. You can <a href='[Link]'>Login</a> now! "); } } catch (Exception ex) { [Link](this, [Link](), "Message", "alert('Error occured : " + [Link]() + "');", true); return; } finally { [Link](); [Link](); } } [Link] Section: Source code of [Link]
Design the [Link] 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" /> [Link] Code for [Link] page In the code behind file ([Link]) write the code as: Imports [Link] Imports [Link] Imports [Link] Imports [Link] Imports [Link] Imports [Link] Dim con As NewSqlConnection([Link]("conStr").Connect ionString) Protected Sub btnSubmit_Click(sender As Object, e As [Link]) [Link] Dim msg As MailMessage Dim cmd As New SqlCommand() Dim ActivationUrl As String = [Link] Dim emailId As String = [Link] Try cmd = New SqlCommand("insert into Tb_Registration (Name,EmailId,Address,ContactNo) values (@Name,@EmailId,@Address,@ContactNo) ", con) [Link]("@Name", [Link]()) [Link]("@EmailId", [Link]()) [Link]("@Address", [Link]()) [Link]("@ContactNo", [Link]())
If [Link] = [Link] Then [Link]() End If [Link]() Sending activation link in the email msg = New MailMessage() Dim smtp As New SmtpClient() emailId = [Link]() 'sender email address [Link] = New MailAddress("YourGmailEmailId@[Link]") 'Receiver email address msg.[To].Add(emailId) [Link] = "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 = [Link]("[Link] UserID=" & FetchUserId(emailId) & "&EmailId=" & emailId) [Link] = "Hi " & [Link]() & "!" & vbLf & "Thanks for showing interest and registring in <a href='[Link] [Link]<a> " & " Please <a href='" & ActivationUrl & "'>click here to activate</a> your account and enjoy our services. " & vbLf & "Thanks!" [Link] = True [Link] = New NetworkCredential("YourGmailEmailId@[Link]","YourGmailPassword") [Link] = 587 [Link] = "[Link]" [Link] = True [Link](msg)
clear_controls() [Link](Me, Me.[GetType](), "Message", "alert('Confirm ation Link to activate account has been sent to your email address');", True) Catch ex As Exception [Link](Me, Me.[GetType](), "Message", "alert('Error occured : " & [Link]() & "');", True) Return Finally ActivationUrl = [Link] emailId = [Link] [Link]() [Link]() 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) [Link]("@EmailId", emailId) If [Link] = [Link] Then [Link]() End If Dim UserID As String = [Link]([Link]()) [Link]() [Link]() Return UserID End Function
Private Sub clear_controls() [Link] = [Link] [Link] = [Link] [Link] = [Link] [Link] = [Link] [Link]() End Sub Add a new page [Link]. 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 ([Link]) and write the code on the page load event as: Imports [Link] Imports [Link] Imports [Link] Protected Sub Page_Load(sender As Object, e As [Link]) Handles [Link] If Not [Link] Then ActivateMyAccount() End If End Sub Private Sub ActivateMyAccount() Dim con As New SqlConnection() Dim cmd As New SqlCommand() Try con = NewSqlConnection([Link]("conStr").ConnectionString) If (Not [Link]([Link]("UserID"))) And ([Link]
lOrEmpty([Link]("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) [Link]("@UserID", [Link]("UserID")) [Link]("@EmailId", [Link]("EmailId")) If [Link] = [Link] Then [Link]() End If [Link]() [Link]("You account has been activated. You can <a href='[Link]'>Login</a> now! ") End If Catch ex As Exception [Link](Me, Me.[GetType](), "Message", "alert('Error occured : " & [Link]() & "');", True) Return Finally [Link]() [Link]() 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 [Link] using both C# and [Link] 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 [Link] 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 [Link] 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 [Link] 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.
<fieldset style="width:320px;"> <legend>Login with remember me option in [Link]</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".
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 [Link] file create the connection string to connect the [Link] 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 (.[Link]) write the code as:.
First include the following required namespaces and write the code as: using [Link]; using [Link]; using [Link]; protected void btnLogin_Click(object sender, EventArgs e) { SqlConnection con=new SqlConnection([Link]["conS tr"].ConnectionString); SqlDataAdapter adp = new SqlDataAdapter(); try { adp = new SqlDataAdapter("CheckLogin_sp", con); [Link]("@UserName", [Link]()); [Link]("@Pwd", [Link]()); [Link] = [Link]; if ([Link] == [Link]) {
[Link](); } SqlDataReader dr = [Link](); if ([Link]) { if ([Link]) { [Link](); [Link]["UserName"].Value = [Link](); [Link]["Pwd"].Value = [Link](); [Link]["UserName"].Expires = [Link](30); [Link]["Pwd"].Expires = [Link](30); } else { [Link]["UserName"].Expires = [Link](-1); [Link]["Pwd"].Expires = [Link](-1); } [Link](this, [Link](), "Message", "alert('Login Successful');", true);
} else { [Link](this, [Link](), "Message", "alert('Invalid UserName or Password');", true); } } catch (Exception ex) { [Link](this, [Link](), "Message", "alert('Error occurred : " + [Link]() + "');", true); } finally { [Link](); [Link](); } } protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack)
{ if ([Link]["UserName"] != null && [Link]["Pwd"] != null) { [Link] = [Link]["UserName"].Value; [Link]("value", [Link]["Pwd"].Value); [Link] = true; } } } [Link] Code to implement remember me checkbox option in login form In the code behind file (.[Link]) write the code as:
First import the following required namespaces and write the code as: Imports [Link] Imports [Link] Imports [Link] Protected Sub btnLogin_Click(sender As Object, e As [Link]) Handles [Link] Dim con As New SqlConnection([Link]("conStr").Co nnectionString) Dim adp As New SqlDataAdapter()
Try adp = New SqlDataAdapter("CheckLogin_sp", con) [Link]("@UserName", [Link]()) [Link]("@Pwd", [Link]()) [Link] = [Link] If [Link] = [Link] Then [Link]() End If Dim dr As SqlDataReader = [Link]() If [Link] Then If [Link] Then [Link]() [Link]("UserName").Value = [Link]() [Link]("Pwd").Value = [Link]() [Link]("UserName").Expires = [Link](30) [Link]("Pwd").Expires = [Link](30) Else [Link]("UserName").Expires = [Link](-1) [Link]("Pwd").Expires = [Link](-1)
End If [Link](Me, Me.[GetType](), "Message", "alert('Log in Successful');", True) Else [Link](Me, Me.[GetType](), "Message", "alert('Invali d UserName or Password');", True) End If Catch ex As Exception [Link](Me, Me.[GetType](), "Message", "alert('Error occurred : " & [Link]() & "');", True) Finally [Link]() [Link]() End Try End Sub
Protected Sub Page_Load(sender As Object, e As [Link]) Handles [Link] If Not IsPostBack Then If [Link]("UserName") IsNot Nothing AndAlso [Link]("Pwd") Is Not Nothing Then [Link] = [Link]("UserName").Value [Link]("value", [Link]("Pwd").Value)
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."
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 [Link] 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/[Link]" 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.
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 [Link] fig file create the connection string to connect the [Link] 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 (.[Link]) write the code as: First include the required namespaces and then write the below mentioned code: using [Link]; using [Link]; using [Link]; SqlConnection con = newSqlConnection([Link]["con"].ConnectionStri ng); protected void Page_Load(object sender, EventArgs e) { if ([Link] == [Link]) { [Link](); } if (![Link]) { BindEmpGrid(); } } #region "Bind GridView" private void BindEmpGrid() { SqlDataAdapter adp = new SqlDataAdapter(); DataTable dt = new DataTable(); try {
adp = new SqlDataAdapter("BindEmpGrid_Sp", con); [Link](dt); if ([Link] > 0) { [Link] = dt; [Link](); } else { [Link] = null; [Link](); } } catch (Exception ex) { [Link](this, [Link](), "Message", "alert('Err or occured : " + [Link]() + "');", true); } finally { [Link](); [Link](); [Link](); [Link](); } } #endregion #region "GridView Paging" protected void grdEmp_PageIndexChanging(object sender, GridViewPageEventArg s e) { [Link] = [Link]; 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([Link][[Link]].Value); cmd = new SqlCommand("DeleteEmpRecord_Sp", con); [Link]("@EmpId", [Link]).Value = empId; [Link] = [Link]; [Link](); BindEmpGrid(); [Link](Page, [Link](),[Link]().ToString(), "alert('Record has been deleted successfully');", true); } catch (Exception ex) { [Link](this, [Link](), "Message", "alert('Err or occured : " + [Link]() + "');", true); } finally { [Link](); [Link](); } } #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 [Link]) {
//Finiding checkbox control in gridview for particular row CheckBox chk = (CheckBox)[Link]("chkDel"); if ([Link]) { //get EmpId from DatakeyNames from gridview int empid = Convert.ToInt32([Link][[Link]].Value); cmd = new SqlCommand("DeleteEmpRecord_Sp", con); [Link]("@EmpId", [Link]).Value = empid; [Link] = [Link]; [Link](); } } [Link] = -1; BindEmpGrid(); [Link](Page, [Link](),[Link]().ToString(), "alert('Selected Records has been deleted successfully');", true); } catch (Exception ex) { [Link](this, [Link](), "Message", "alert('Err or occured : " + [Link]() + "');", true); } finally { [Link](); [Link](); } } #endregion
[Link] 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 (.[Link]) write the code as: First include the required namespaces and then write the below mentioned code Imports [Link] Imports [Link] Imports [Link] Dim con As NewSqlConnection([Link]("con").Con nectionString) Protected Sub Page_Load(sender As Object, e As [Link]) Handles [Link] If [Link] = [Link] Then [Link]() End If If Not [Link] 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) [Link](dt) If [Link] > 0 Then [Link] = dt [Link]() Else [Link] = Nothing [Link]() End If Catch ex As Exception [Link](Me, Me.[GetType](), "Message", "alert('Er ror occured : " & [Link]() & "');", True) Finally [Link]()
[Link]() [Link]() End Try End Sub #End Region #Region "GridView paging" Protected Sub grdEmp_PageIndexChanging(sender As Object, e [Link]) Handles [Link] xChanging [Link] = [Link] BindEmpGrid() End Sub #End Region Protected Sub grdEmp_RowDeleting(sender As Object, e [Link]) Handles [Link] eting Dim cmd As New SqlCommand() Try 'get EmpId from DatakeyNames from gridview Dim empId As Integer = Convert.ToInt32([Link]([Link]).Value ) cmd = New SqlCommand("DeleteEmpRecord_Sp", con) [Link]("@EmpId", [Link]).Value = empId [Link] = [Link] [Link]() BindEmpGrid() [Link](Page, Page.[GetType] (),[Link]().ToString(), "alert('Record has been deleted successfully');", True) Catch ex As Exception [Link](Me, Me.[GetType](), "Message", "alert('Er ror occured : " & [Link]() & "');", True) Finally [Link]() [Link]() End Try
End Sub Protected Sub btnDelete_Click(sender As Object, e As [Link]) Dim cmd As New SqlCommand() Try 'Loop through all the rows in gridview For Each grv As GridViewRow In [Link] 'Finiding checkbox control in gridview for particular row Dim chk As CheckBox = DirectCast([Link]("chkDel"), CheckBox) If [Link] Then 'get EmpId from DatakeyNames from gridview Dim empid As Integer = Convert.ToInt32([Link]([Link]). Value) cmd = New SqlCommand("DeleteEmpRecord_Sp", con) [Link]("@EmpId", [Link]).Value = empid [Link] = [Link] [Link]() End If Next [Link] = -1 BindEmpGrid() [Link](Page, Page.[GetType] (),[Link]().ToString(), "alert('Selected Records has been deleted successfully');", True) Catch ex As Exception [Link](Me, Me.[GetType](), "Message", "alert('Er ror occured : " & [Link]() & "');", True) Finally [Link]() [Link]() End Try End Sub
How to bind and implement search gridview records in [Link] | 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 [Link] using both C#.Net and [Link] languages.
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 [Link] 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 [Link] and Bind empty GridView with header and custom message Implementation: Lets create sample [Link] 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:
Data Type
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 [Link] file create the connection string to connect the [Link] 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>
{ BindEmpGrid(); [Link] = false; } } private void BindEmpGrid() { SqlDataAdapter adp = new SqlDataAdapter(); DataTable dt = new DataTable(); try { adp = new SqlDataAdapter("BindEmpGrid_Sp", con); [Link](dt); if ([Link] > 0) { [Link] = dt; [Link](); } else { [Link] = null; [Link](); } } catch (Exception ex) { [Link](this, [Link](), "Message", "alert('Err or occured : " + [Link]() + "');", true); } finally { [Link](); [Link](); [Link](); [Link](); } }
protected void ddlSearchBy_SelectedIndexChanged(object sender, EventArgs e) { if ([Link] == "All") { [Link] = [Link]; [Link] = false; } else { [Link] = true; [Link] = [Link]; [Link](); } } protected void btnSearch_Click(object sender, EventArgs e) { DataTable dt = new DataTable(); SqlCommand cmd = new SqlCommand(); SqlDataAdapter adp=new SqlDataAdapter(); try { if ([Link] == "Emp Name") { getEmpRecords([Link], [Link]()); } else if ([Link] == "City") { getEmpRecords([Link], [Link]()); } else if ([Link] == "Salary") { getEmpRecords([Link], [Link]()); }
else { getEmpRecords([Link], [Link]()); } } catch (Exception ex) { [Link](this, [Link](), "Message", "alert('Err or occured : " + [Link]() + "');", true); } finally { [Link](); [Link](); [Link](); [Link](); } } 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); [Link] = [Link]; [Link]("@SearchBy", searchBy); [Link]("@SearchVal", searchVal); [Link] = cmd; [Link](dt); if ([Link] > 0) { [Link] = dt; [Link](); }
else { [Link] = dt; [Link](); } } catch (Exception ex) { [Link](this, [Link](), "Message", "alert('Err or occured : " + [Link]() + "');", true); } finally { [Link](); [Link](); [Link](); [Link](); } } protected void grdEmp_PageIndexChanging(object sender, GridViewPageEventArg s e) { [Link] = [Link]; BindEmpGrid(); }
[Link] Code
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 (.[Link]) write the code as: First import the following namespaces Imports [Link] Imports [Link] Imports [Link] Dim con As NewSqlConnection([Link]("con").Con nectionString) Protected Sub Page_Load(sender As Object, e As [Link]) Handles [Link] If [Link] = [Link] Then [Link]() End If If Not [Link] Then BindEmpGrid() [Link] = 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) [Link](dt) If [Link] > 0 Then [Link] = dt [Link]() Else [Link] = Nothing
[Link]() End If Catch ex As Exception [Link](Me, Me.[GetType](), "Message", "alert('Er ror occured : " & [Link]() & "');", True) Finally [Link]() [Link]() [Link]() [Link]() End Try End Sub Protected Sub ddlSearchBy_SelectedIndexChanged(sender As Object, e [Link]) Handles [Link] If [Link] = "All" Then [Link] = [Link] [Link] = False Else [Link] = True [Link] = [Link] [Link]() End If End Sub Protected Sub btnSearch_Click(sender As Object, e As [Link]) [Link] Dim dt As New DataTable() Dim cmd As New SqlCommand() Dim adp As New SqlDataAdapter() Try If [Link] = "Emp Name" Then getEmpRecords([Link], [Link]()) ElseIf [Link] = "City" Then getEmpRecords([Link], [Link]()) ElseIf [Link] = "Salary" Then getEmpRecords([Link], [Link]()) Else
getEmpRecords([Link], [Link]()) End If Catch ex As Exception [Link](Me, Me.[GetType](), "Message", "alert('Er ror occured : " & [Link]() & "');", True) Finally [Link]() [Link]() [Link]() [Link]() 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) [Link] = [Link] [Link]("@SearchBy", searchBy) [Link]("@SearchVal", searchVal) [Link] = cmd [Link](dt) If [Link] > 0 Then [Link] = dt [Link]() Else [Link] = dt [Link]() End If Catch ex As Exception [Link](Me, Me.[GetType](), "Message", "alert('Er ror occured : " & [Link]() & "');", True) Finally [Link]() [Link]() [Link]()
[Link]() End Try End Sub Protected Sub grdEmp_PageIndexChanging(sender As Object, e [Link]) Handles [Link] xChanging [Link] = [Link] BindEmpGrid() End Sub