Stored Procedure

Firstly, create a Stored Procedure for performing CRUD operation on database from ASP.NET page. In the following Stored procedure I have mentioned the entire query in one stored procedure like Select, Add, Update and Delete. All the operation is based on Event or status which will send from ASP.NET page.

Stored Procedure is based on Table "Employee".

Column Name DataType
Id int
FirstName varchar(50)
LastName varchar(50)
PhoneNumber nvarchar(15)
EmailAddress nvarchar(50)
Salary decimal(18, 2)

Below find the stored procedure for above table. I have used if-else condition to perform all operations in single stored procedure. Based on Event which is sent by ASP.NET page the query will be executed.

  1. CREATE PROC [dbo].[usp_GridViewExample]
  2. (
  3. @EmpId int=0,@FirstName varchar(50)=Null,@LastName varchar(50)=Null,@PhoneNumber nvarchar(15)=Null,
  4. @EmailAddress nvarchar(50)=Null,@Salary decimal=Null,@Event varchar(10)
  5. )
  6. AS
  7. BEGIN
  8. IF(@Event='Select')
  9. BEGIN
  10. SELECT * FROM Employee ORDER BY FirstName ASC;
  11. END
  12. ELSE IF(@Event='Add')
  13. BEGIN
  14. INSERT INTO Employee (FirstName,LastName,PhoneNumber,EmailAddress,Salary,CreatedDate) VALUES(@FirstName,@LastName,@PhoneNumber,@EmailAddress,@Salary,GETDATE());
  15. END
  16. ELSE IF(@Event='Update')
  17. BEGIN
  18. UPDATE Employee SET FirstName=@FirstName,LastName=@LastName,PhoneNumber=@PhoneNumber,EmailAddress=@EmailAddress,Salary=@Salary where Id=@EmpId;
  19. END
  20. ELSE
  21. BEGIN
  22. DELETE FROM Employee WHERE Id=@EmpId;
  23. END
  24. END
GridViewDemo.aspx

This is a UI of application. In this I have created Add Employee Panel where we can add new employee and below this I have added a gridview where we can do Edit and Delete as well as you can see all the records,
  1. <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="GridViewDemo.aspx.cs" Inherits="GridViewDemo.GridViewDemo" %>
  2. <!DOCTYPE html>
  3. <html xmlns="http://www.w3.org/1999/xhtml">
  4. <head runat="server">
  5. <title></title>
  6. <style>
  7. td {
  8. align=center;
  9. }
  10. </style>
  11. </head>
  12. <body>
  13. <form id="form1" runat="server">
  14. <div align="center">
  15. <div style="border: 1px Solid #0094ff; width: 70%;">
  16. <table>
  17. <tr>
  18. <td colspan="3" align="center">
  19. <h2>Employee Management System</h2> </td>
  20. </tr>
  21. <tr>
  22. <td>First Name </td>
  23. <td>
  24. <asp:TextBox runat="server" ID="txtFirstName" ValidationGroup="add"></asp:TextBox>
  25. </td>
  26. <td>
  27. <asp:RequiredFieldValidator runat="server" ID="reqFirstName" ControlToValidate="txtFirstName" ForeColor="Red" ErrorMessage="First Name Requierd" EnableClientScript="true" ValidationGroup="add"></asp:RequiredFieldValidator>
  28. </td>
  29. </tr>
  30. <tr>
  31. <td>Last Name </td>
  32. <td>
  33. <asp:TextBox runat="server" ID="txtLastName" ValidationGroup="add"></asp:TextBox>
  34. </td>
  35. <td>
  36. <asp:RequiredFieldValidator runat="server" ID="reqLastName" ControlToValidate="txtLastName" ForeColor="Red" ErrorMessage="Last Name Required" EnableClientScript="true" ValidationGroup="add"></asp:RequiredFieldValidator>
  37. </td>
  38. </tr>
  39. <tr>
  40. <td>Phone Number </td>
  41. <td>
  42. <asp:TextBox runat="server" ID="txtPhoneNumber"></asp:TextBox>
  43. </td>
  44. <td></td>
  45. </tr>
  46. <tr>
  47. <td>Emial Address </td>
  48. <td>
  49. <asp:TextBox runat="server" ID="txtEmailAddress" ValidationGroup="add"></asp:TextBox>
  50. </td>
  51. <td>
  52. <asp:RequiredFieldValidator runat="server" ID="reqEmailAddress" ControlToValidate="txtEmailAddress" ForeColor="Red" ErrorMessage="Email Address Required" EnableClientScript="true" ValidationGroup="add"></asp:RequiredFieldValidator>
  53. </td>
  54. </tr>
  55. <tr>
  56. <td>Salary </td>
  57. <td>
  58. <asp:TextBox runat="server" ID="txtSalary" ValidationGroup="add"></asp:TextBox>
  59. </td>
  60. <td>
  61. <asp:RequiredFieldValidator runat="server" ID="reqSalary" ControlToValidate="txtSalary" ForeColor="Red" ErrorMessage="Salary Required" EnableClientScript="true" ValidationGroup="add"></asp:RequiredFieldValidator>
  62. </td>
  63. </tr>
  64. <tr>
  65. <td colspan="3" align="center">
  66. <asp:Button runat="server" ID="btnAddEmployee" Text="Add" OnClick="btnAddEmployee_Click" Style="height: 26px" Width="37px" ValidationGroup="add" /> </td>
  67. </tr>
  68. <tr>
  69. <td colspan="3" align="center">
  70. <br />
  71. <asp:Label runat="server" ID="lblMessage"></asp:Label>
  72. <br />
  73. <br /> </td>
  74. </tr>
  75. <tr>
  76. <td colspan="3">
  77. <asp:GridView ID="grvEmployee" runat="server" AllowPaging="true" AutoGenerateColumns="false" Width="900px" HeaderStyle-ForeColor="blue" OnPageIndexChanging="grvEmployee_PageIndexChanging" OnRowCancelingEdit="grvEmployee_RowCancelingEdit" OnRowDeleting="grvEmployee_RowDeleting" OnRowEditing="grvEmployee_RowEditing" OnRowUpdating="grvEmployee_RowUpdating">
  78. <Columns>
  79. <asp:TemplateField HeaderText="EmpId">
  80. <ItemTemplate>
  81. <asp:Label runat="server" ID="lblEmpId" Text='<%#Eval("id") %>'></asp:Label>
  82. </ItemTemplate>
  83. </asp:TemplateField>
  84. <asp:TemplateField HeaderText="FirstName">
  85. <ItemTemplate>
  86. <asp:Label runat="server" ID="lblFirstName" Text='<%#Eval("FirstName") %>'></asp:Label>
  87. </ItemTemplate>
  88. <EditItemTemplate>
  89. <asp:TextBox runat="server" ID="txtFirstName" Text='<%#Eval("FirstName") %>'></asp:TextBox>
  90. </EditItemTemplate>
  91. </asp:TemplateField>
  92. <asp:TemplateField HeaderText="LastName">
  93. <ItemTemplate>
  94. <asp:Label runat="server" ID="lblLastName" Text='<%#Eval("LastName") %>'></asp:Label>
  95. </ItemTemplate>
  96. <EditItemTemplate>
  97. <asp:TextBox runat="server" ID="txtLastName" Text='<%#Eval("LastName") %>'></asp:TextBox>
  98. </EditItemTemplate>
  99. </asp:TemplateField>
  100. <asp:TemplateField HeaderText="Phone No.">
  101. <ItemTemplate>
  102. <asp:Label runat="server" ID="lblPhoneNumber" Text='<%#Eval("PhoneNumber") %>'></asp:Label>
  103. </ItemTemplate>
  104. <EditItemTemplate>
  105. <asp:TextBox runat="server" ID="txtPhoneNumber" Text='<%#Eval("PhoneNumber") %>'></asp:TextBox>
  106. </EditItemTemplate>
  107. </asp:TemplateField>
  108. <asp:TemplateField HeaderText="Email">
  109. <ItemTemplate>
  110. <asp:Label runat="server" ID="lblEmailAddress" Text='<%#Eval("EmailAddress") %>'></asp:Label>
  111. </ItemTemplate>
  112. <EditItemTemplate>
  113. <asp:TextBox runat="server" ID="txtEmailAddress" Text='<%#Eval("EmailAddress") %>'></asp:TextBox>
  114. </EditItemTemplate>
  115. </asp:TemplateField>
  116. <asp:TemplateField HeaderText="Salary">
  117. <ItemTemplate>
  118. <asp:Label runat="server" ID="lblSalary" Text='<%#Eval("Salary") %>'></asp:Label>
  119. </ItemTemplate>
  120. <EditItemTemplate>
  121. <asp:TextBox runat="server" ID="txtSalary" Text='<%#Eval("Salary") %>'></asp:TextBox>
  122. </EditItemTemplate>
  123. </asp:TemplateField>
  124. <asp:TemplateField HeaderText="Manage">
  125. <ItemTemplate>
  126. <asp:LinkButton runat="server" ID="btnEdit" Text="Edit" CommandName="Edit" />
  127. <br /> <span onclick="return confirm('Are you sure you want to delete this record?')">
  128. <asp:LinkButton runat="server" ID="btnDelete" Text="Delete" CommandName="Delete" />
  129. </span> </ItemTemplate>
  130. <EditItemTemplate>
  131. <asp:LinkButton runat="server" ID="btnUpdate" Text="Update" CommandName="Update" />
  132. <br />
  133. <asp:LinkButton runat="server" ID="btnCancel" Text="Cancel" CommandName="Cancel" /> </EditItemTemplate>
  134. </asp:TemplateField>
  135. </Columns>
  136. </asp:GridView>
  137. </td>
  138. </tr>
  139. </table>
  140. </div>
  141. </div> <a href="http://www.nextprogramming.com/2014/09/stored-procedure-in-sql-server-advantages-of-stored-procedure-and-how-to-use-stored-procedure">Click Here</a> </form>
  142. </body>
  143. </html>
GridViewDemo.aspx.cs

It’s a .cs file or called code-behind file where I have written the entire login for CRUD operation in GridView using stored procedure. I have created Connection for database connectivity, on Add button I have added a new employee in database. I have also used here validation using Required Field Validator. Edit and Delete operation have been done in GridView.

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Configuration;
  4. using System.Data;
  5. using System.Data.SqlClient;
  6. using System.Linq;
  7. using System.Web;
  8. using System.Web.UI;
  9. using System.Web.UI.WebControls;
  10. namespace GridViewDemo
  11. {
  12. public partial class GridViewDemo : System.Web.UI.Page
  13. {
  14. private string strConnectionString = ConfigurationManager.ConnectionStrings["myconnection"].ConnectionString;
  15. private SqlCommand _sqlCommand;
  16. private SqlDataAdapter _sqlDataAdapter;
  17. DataSet _dtSet;
  18. protected void Page_Load(object sender, EventArgs e)
  19. {
  20. if (!IsPostBack)
  21. {
  22. BindEmployeeData();
  23. }
  24. }
  25. public void CreateConnection()
  26. {
  27. SqlConnection _sqlConnection = new SqlConnection(strConnectionString);
  28. _sqlCommand = new SqlCommand();
  29. _sqlCommand.Connection = _sqlConnection;
  30. }
  31. public void OpenConnection()
  32. {
  33. _sqlCommand.Connection.Open();
  34. }
  35. public void CloseConnection()
  36. {
  37. _sqlCommand.Connection.Close();
  38. }
  39. public void DisposeConnection()
  40. {
  41. _sqlCommand.Connection.Dispose();
  42. }
  43. public void BindEmployeeData()
  44. {
  45. try
  46. {
  47. CreateConnection();
  48. OpenConnection();
  49. _sqlCommand.CommandText = "usp_GridViewExample";
  50. _sqlCommand.CommandType = CommandType.StoredProcedure;
  51. _sqlCommand.Parameters.AddWithValue("@Event", "Select");
  52. _sqlDataAdapter = new SqlDataAdapter(_sqlCommand);
  53. _dtSet = new DataSet();
  54. _sqlDataAdapter.Fill(_dtSet);
  55. grvEmployee.DataSource = _dtSet;
  56. grvEmployee.DataBind();
  57. }
  58. catch (Exception ex)
  59. {
  60. Response.Redirect("The Error is " + ex);
  61. }
  62. finally
  63. {
  64. CloseConnection();
  65. DisposeConnection();
  66. }
  67. }
  68. protected void btnAddEmployee_Click(object sender, EventArgs e)
  69. {
  70. try
  71. {
  72. CreateConnection();
  73. OpenConnection();
  74. _sqlCommand.CommandText = "usp_GridViewExample";
  75. _sqlCommand.CommandType = CommandType.StoredProcedure;
  76. _sqlCommand.Parameters.AddWithValue("@Event", "Add");
  77. _sqlCommand.Parameters.AddWithValue("@FirstName", Convert.ToString(txtFirstName.Text.Trim()));
  78. _sqlCommand.Parameters.AddWithValue("@LastName", Convert.ToString(txtLastName.Text.Trim()));
  79. _sqlCommand.Parameters.AddWithValue("@PhoneNumber", Convert.ToString(txtPhoneNumber.Text.Trim()));
  80. _sqlCommand.Parameters.AddWithValue("@EmailAddress", Convert.ToString(txtEmailAddress.Text.Trim()));
  81. _sqlCommand.Parameters.AddWithValue("@Salary", Convert.ToDecimal(txtSalary.Text));
  82. int result = Convert.ToInt32(_sqlCommand.ExecuteNonQuery());
  83. if (result > 0)
  84. {
  85. lblMessage.Text = "Record Added Successfully";
  86. lblMessage.ForeColor = System.Drawing.Color.Green;
  87. BindEmployeeData();
  88. }
  89. else
  90. {
  91. lblMessage.Text = "Failed";
  92. lblMessage.ForeColor = System.Drawing.Color.Red;
  93. }
  94. }
  95. catch (Exception ex)
  96. {
  97. lblMessage.Text = "Check your input data";
  98. lblMessage.ForeColor = System.Drawing.Color.Red;
  99. }
  100. finally
  101. {
  102. CloseConnection();
  103. DisposeConnection();
  104. }
  105. }
  106. protected void grvEmployee_RowEditing(object sender, GridViewEditEventArgs e)
  107. {
  108. grvEmployee.EditIndex = e.NewEditIndex;
  109. BindEmployeeData();
  110. }
  111. protected void grvEmployee_RowDeleting(object sender, GridViewDeleteEventArgs e)
  112. {
  113. try
  114. {
  115. CreateConnection();
  116. OpenConnection();
  117. Label id = (Label)grvEmployee.Rows[e.RowIndex].FindControl("lblEmpId");
  118. _sqlCommand.CommandText = "usp_GridViewExample";
  119. _sqlCommand.Parameters.AddWithValue("@Event", "Delete");
  120. _sqlCommand.Parameters.AddWithValue("@EmpId", Convert.ToInt32(id.Text));
  121. _sqlCommand.CommandType = CommandType.StoredProcedure;
  122. int result = Convert.ToInt32(_sqlCommand.ExecuteNonQuery());
  123. if (result > 0)
  124. {
  125. lblMessage.Text = "Record Deleted Successfully";
  126. lblMessage.ForeColor = System.Drawing.Color.Green;
  127. grvEmployee.EditIndex = -1;
  128. BindEmployeeData();
  129. }
  130. else
  131. {
  132. lblMessage.Text = "Failed";
  133. lblMessage.ForeColor = System.Drawing.Color.Red;
  134. BindEmployeeData();
  135. }
  136. }
  137. catch (Exception ex)
  138. {
  139. lblMessage.Text = "Check your input data";
  140. lblMessage.ForeColor = System.Drawing.Color.Red;
  141. }
  142. finally
  143. {
  144. CloseConnection();
  145. DisposeConnection();
  146. }
  147. }
  148. protected void grvEmployee_RowUpdating(object sender, GridViewUpdateEventArgs e)
  149. {
  150. try
  151. {
  152. CreateConnection();
  153. OpenConnection();
  154. Label Empid = (Label)grvEmployee.Rows[e.RowIndex].FindControl("lblEmpId");
  155. TextBox txtFirstName = (TextBox)grvEmployee.Rows[e.RowIndex].FindControl("txtFirstName");
  156. TextBox txtLastName = (TextBox)grvEmployee.Rows[e.RowIndex].FindControl("txtLastName");
  157. TextBox txtPhoneNumber = (TextBox)grvEmployee.Rows[e.RowIndex].FindControl("txtPhoneNumber");
  158. TextBox txtEmailAddress = (TextBox)grvEmployee.Rows[e.RowIndex].FindControl("txtEmailAddress");
  159. TextBox txtSalary = (TextBox)grvEmployee.Rows[e.RowIndex].FindControl("txtSalary");
  160. _sqlCommand.CommandText = "usp_GridViewExample";
  161. _sqlCommand.CommandType = CommandType.StoredProcedure;
  162. _sqlCommand.Parameters.AddWithValue("@Event", "Update");
  163. _sqlCommand.Parameters.AddWithValue("@FirstName", Convert.ToString(txtFirstName.Text.Trim()));
  164. _sqlCommand.Parameters.AddWithValue("@LastName", Convert.ToString(txtLastName.Text.Trim()));
  165. _sqlCommand.Parameters.AddWithValue("@PhoneNumber", Convert.ToString(txtPhoneNumber.Text.Trim()));
  166. _sqlCommand.Parameters.AddWithValue("@EmailAddress", Convert.ToString(txtEmailAddress.Text.Trim()));
  167. _sqlCommand.Parameters.AddWithValue("@Salary", Convert.ToDecimal(txtSalary.Text));
  168. _sqlCommand.Parameters.AddWithValue("@EmpId", Convert.ToDecimal(Empid.Text));
  169. int result = Convert.ToInt32(_sqlCommand.ExecuteNonQuery());
  170. if (result > 0)
  171. {
  172. lblMessage.Text = "Record Updated Successfully";
  173. lblMessage.ForeColor = System.Drawing.Color.Green;
  174. grvEmployee.EditIndex = -1;
  175. BindEmployeeData();
  176. }
  177. else
  178. {
  179. lblMessage.Text = "Failed";
  180. lblMessage.ForeColor = System.Drawing.Color.Red;
  181. }
  182. }
  183. catch (Exception ex)
  184. {
  185. lblMessage.Text = "Check your input data";
  186. lblMessage.ForeColor = System.Drawing.Color.Red;
  187. }
  188. finally
  189. {
  190. CloseConnection();
  191. DisposeConnection();
  192. }
  193. }
  194. protected void grvEmployee_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
  195. {
  196. grvEmployee.EditIndex = -1;
  197. BindEmployeeData();
  198. }
  199. protected void grvEmployee_PageIndexChanging(object sender, GridViewPageEventArgs e)
  200. {
  201. grvEmployee.PageIndex = e.NewPageIndex;
  202. BindEmployeeData();
  203. }
  204. }
  205. }
Conclusion

Today we learned how to perform CRUD operation in ASP.NET GridView using Stored Procedure with Validation.