Authenticate, Search And Add Records In GridView In ASP.Net

Today, I am going to show you how to create a website project that's able to authenticate login and add and search data in DataGridViews, in ASP.NET and using C#.
 
Introduction
 
The ProDatabase is a website project created in ASP.NET based on C# language (Visual Studio 2010). This project is just an example of something used in the Ministry of Education in Afghanistan, in the field of procurement. I have not included the registration form because if someone wants to use it, he/she should write an application letter for a username and password; then, the administrator can assign him/her access. However, you can add your registration form.
 
NOTE: If you want to download the project, then you can easily do that. But, you have to create an empty C# website project first and then select and copy all the files from what you have downloaded and paste them in your project.
 
Let’s start.
 
1. Open Visual Studio and select new C# ASP.NET website (not an empty website at this stage). So, you have two pages named as Default.aspx and About.aspx and four folders named Accounts, App_Data, Scripts and styles along with a master page with web.config file and Global.asax. For the moment, forget about these things. Just select the Account and App_Data folders and delete them. Good, no problem.
 
2. Now, click on your website and add a new item, a web form. Name it as login.aspx ( do not select its master page option, because here we use it to avoid the access to the other pages. Thus it should be an empty form). Now, add two textboxes (TextBox1, and TextBox2), a button (Button1), and a label to give you the right message. Of course, make this page as default start page, so that it loads first. For this, right click on it (in Solution Explorer) and make it the Start Page, like this:
 
 
 
Have you done it? If not, here is the source code for designing such a form:
  1. <%@ Page Title="Login" Language="C#" AutoEventWireup="true" CodeFile="Login.aspx.cs" Inherits="Login" %>    
  2. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">    
  3. <html xmlns="http://www.w3.org/1999/xhtml">    
  4. <head runat="server">    
  5.     <title></title>    
  6.     <style type="text/css">    
  7.         .style1    
  8.         {    
  9.             text-align: center;    
  10.             height: 39px;    
  11.         }    
  12.         .style2    
  13.         {    
  14.             font-size: xx-large;    
  15.             color: #FFFFFF;    
  16.         }    
  17.     </style>    
  18. </head>    
  19. <body style="width: 535px; height: 221px; margin-left: 400px; margin-top: 174px; margin-bottom: 45px">    
  20.     <p class="style1"             
  21.         style="width: 543px; margin-bottom: 19px; background-color: #006699; margin-right: 0px;">    
  22.         <span class="style2">Login</span><br />    
  23.     </p>    
  24.     <form id="form1" runat="server">    
  25.     <div class="style1"     
  26.         style="border-style: 0; border-width: 1px; border-color: #008000; width: 543px;">    
  27.          Username     
  28.         <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>    
  29.         <br />    
  30.         <br />    
  31.  Password     
  32.         <asp:TextBox ID="TextBox2" runat="server" TextMode="Password"></asp:TextBox>    
  33.         <br />    
  34.         <br />    
  35.         <asp:Button ID="Button1" runat="server" style="margin-left: 64px; height: 26px;"     
  36.             Text="Login" onclick="Button1_Click" />               
  37.         <asp:Label ID="Label1" runat="server"></asp:Label>    
  38.  <br />    
  39.         <p style="height: 25px; background-color: #006699"></p><br />          
  40.     </div>    
  41.     </form>    
  42. </body>    
  43. </html>   
3. Very smart !! Now, add another item, a SQL database and name it database.mdf. This will automatically create a folder named App_Data and will settle there. Double click on it and the Server Explorer will open. Now, make a new table in the db and name it UserData. This table should have two fields, UserName and Password. (It will be better to click on the table and select show table data and add a user or two, because we don’t have registration system.)
 
4. Now, click on the login page code side and write this code.
  1. using System;    
  2. using System.Collections.Generic;     
  3. using System.Web;    
  4. using System.Web.UI;    
  5. using System.Web.UI.WebControls;    
  6. using System.Data.SqlClient;    
  7. using System.Configuration;    
  8.     
  9. public partial class Login : System.Web.UI.Page    
  10. {     
  11.     protected void Button1_Click(object sender, EventArgs e)    
  12.     {    
  13.         SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["regConnectionString"].ConnectionString);    
  14.         con.Open();    
  15.         SqlCommand cmd = new SqlCommand("select COUNT(*)FROM UserData WHERE UserName='" + TextBox1.Text + "' and Password='" + TextBox2.Text + "'");    
  16.         cmd.Connection = con;    
  17.         int OBJ = Convert.ToInt32(cmd.ExecuteScalar());    
  18.         if (OBJ > 0)    
  19.         {    
  20.             Session["name"] = TextBox1.Text;    
  21.             Response.Redirect("default.aspx");    
  22.         }    
  23.         else    
  24.         {    
  25.             Label1.Text = "Invalid username or password";                 
  26.         }    
  27.     }    
  28. }  
5. Now, go to the Master page and try to make it something like this, or as per your preference. I have added two extra menu items and a footer. I guess there is no need for its source code.
 
 
 
6. Was that hard to understand? If not, then let's continue. Well, add another form and name it as Projects.aspx. This is the form that we use for adding the projects to our database (from now on, all our new forms should inherit our Master page. So, select its Master page option). Very simple! Just add a table with two columns, eight rows, some textboxes and a GridView. Try to make something like the following:
 
 
 
If you have not done it yet, don’t worry. Here is the source code:
  1. <%@ Page Title="Projects" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true" CodeFile="Projects.aspx.cs" Inherits="Projects" %>    
  2. <asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" Runat="Server">    
  3.     </asp:Content>    
  4. <asp:Content ID="Content2" ContentPlaceHolderID="MainContent" Runat="Server">    
  5.     <p>Please Enter all the required fields to the textboxes and click ADD</p>    
  6.        <table align="left" cellspacing="1" class="style7">    
  7.         <tr>    
  8.             <td class="style10">    
  9.                 ID</td>    
  10.             <td class="style11">    
  11.                 <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>      
  12.             </td>    
  13.         </tr>    
  14.         <tr>    
  15.             <td class="style10">    
  16.                 Name</td>    
  17.             <td class="style11">    
  18.                 <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>    
  19.             </td>    
  20.         </tr>    
  21.         <tr>    
  22.             <td class="style10">    
  23.                 Price</td>    
  24.             <td class="style11">    
  25.                 <asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>    
  26.             </td>    
  27.         </tr>    
  28.         <tr>    
  29.             <td class="style10">    
  30.                 Company</td>    
  31.             <td class="style11">    
  32.                 <asp:TextBox ID="TextBox4" runat="server"></asp:TextBox>    
  33.             </td>    
  34.         </tr>    
  35.         <tr>    
  36.             <td class="style10">    
  37.                 Recieve Date</td>    
  38.             <td class="style11">    
  39.                 <asp:TextBox ID="TextBox5" runat="server"></asp:TextBox>    
  40.             </td>    
  41.         </tr>    
  42.         <tr>    
  43.             <td class="style12">    
  44.                 Sent Date</td>    
  45.             <td class="style13">    
  46.                 <asp:TextBox ID="TextBox6" runat="server"></asp:TextBox>    
  47.             </td>    
  48.         </tr>    
  49.         <tr>    
  50.             <td class="style12">    
  51.                 Budget</td>    
  52.             <td class="style13">    
  53.                 <asp:TextBox ID="TextBox7" runat="server"></asp:TextBox>    
  54.             </td>    
  55.         </tr>    
  56.         <tr>    
  57.             <td class="style12">    
  58.                 Remarks</td>    
  59.             <td class="style13">    
  60.                 <asp:TextBox ID="TextBox8" runat="server"></asp:TextBox>    
  61.             </td>    
  62.         </tr>    
  63.         <tr>    
  64.             <td class="style12">    
  65.                  </td>    
  66.             <td class="style13">    
  67.                 <br />    
  68.  <asp:Button ID="Button1" runat="server" style="margin-left: 36px" Text="ADD"     
  69.                     Width="53px" onclick="Button1_Click1" />    
  70.                 <br />    
  71.                 <br />    
  72.                 <br />    
  73.             </td>    
  74.         </tr>    
  75.     </table>     
  76. <asp:GridView ID="GridView1" runat="server" AllowPaging="True"     
  77.     AutoGenerateColumns="False" BackColor="#CCCCCC" BorderColor="#999999"     
  78.     BorderStyle="Solid" BorderWidth="3px" CellPadding="4" CellSpacing="2"     
  79.     DataKeyNames="ID" DataSourceID="SqlDataSource1" ForeColor="Black"     
  80.     Height="131px" style="text-align: center" Width="668px">    
  81.     <Columns>    
  82.         <asp:BoundField DataField="ID" HeaderText="ID" ReadOnly="True"     
  83.             SortExpression="ID" />    
  84.         <asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" />    
  85.         <asp:BoundField DataField="Price" HeaderText="Price" SortExpression="Price" />    
  86.         <asp:BoundField DataField="Company" HeaderText="Company"     
  87.             SortExpression="Company" />    
  88.         <asp:BoundField DataField="Rdate" HeaderText="Rdate" SortExpression="Rdate" />    
  89.         <asp:BoundField DataField="Sdate" HeaderText="Sdate" SortExpression="Sdate" />    
  90.         <asp:BoundField DataField="Budget" HeaderText="Budget"     
  91.             SortExpression="Budget" />    
  92.         <asp:BoundField DataField="Files" HeaderText="Files" SortExpression="Files" />    
  93.     </Columns>    
  94.     <FooterStyle BackColor="#CCCCCC" />    
  95.     <HeaderStyle BackColor="Black" Font-Bold="True" ForeColor="White" />    
  96.     <PagerStyle BackColor="#CCCCCC" ForeColor="Black" HorizontalAlign="Left" />    
  97.     <RowStyle BackColor="White" />    
  98.     <SelectedRowStyle BackColor="#000099" Font-Bold="True" ForeColor="White" />    
  99.     <SortedAscendingCellStyle BackColor="#F1F1F1" />    
  100.     <SortedAscendingHeaderStyle BackColor="#808080" />    
  101.     <SortedDescendingCellStyle BackColor="#CAC9C9" />    
  102.     <SortedDescendingHeaderStyle BackColor="#383838" />    
  103. </asp:GridView>    
  104. <asp:SqlDataSource ID="SqlDataSource1" runat="server"     
  105.     ConnectionString="<%$ ConnectionStrings:regConnectionString %>"     
  106.     SelectCommand="SELECT * FROM [projects]"></asp:SqlDataSource>    
  107. </asp:Content>   
Great! Now, click on the code side of the page and write this code:

  1. using System;    
  2. using System.Collections.Generic;    
  3. using System.Linq;    
  4. using System.Web;    
  5. using System.Web.UI;    
  6. using System.Web.UI.WebControls;    
  7. using System.Data.SqlClient;    
  8. using System.Configuration;    
  9. using System.Drawing;    
  10.     
  11. public partial class Projects: System.Web.UI.Page    
  12. {    
  13.     protected void Button1_Click(object sender, EventArgs e)    
  14.     {    
  15.         SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["regConnectionString"].ConnectionString);    
  16.         con.Open();    
  17.         String str = "insert into projects values('" + TextBox1.Text + "','" + TextBox2.Text + "','" + TextBox3.Text + "','" + TextBox4.Text + "','" + TextBox5.Text + "','" + TextBox6.Text + "','" + TextBox7.Text + "','" + TextBox8.Text + "')";    
  18.         SqlCommand cmd = new SqlCommand(str, con);    
  19.         cmd.ExecuteNonQuery();    
  20.         Response.Redirect("projects.aspx");    
  21.         con.Close();    
  22.     }    
  23.    
  24. }   
7. That's it! Now, add another empty web form and name it as search.aspx. This is the form used for searching for a specific record based on the company name in our database (select its Master page option). This time, add one textbox, a button, and a GridView. Try to make it something similar to this: 

 
 
 
Hmm, you need the source code? Here it is:
  1. <%@ Page Title="Search" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true" CodeFile="Search.aspx.cs" Inherits="Search" %>    
  2. <asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" Runat="Server">    
  3. </asp:Content>    
  4. <asp:Content ID="Content2" ContentPlaceHolderID="MainContent" Runat="Server">    
  5.     <p>    
  6.          Please enter the name of the company    
  7.          <asp:TextBox ID="txtSearch" runat="server" />    
  8.          <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Search" />    
  9. <hr />    
  10.  <asp:GridView ID="GridView1" runat="server" BackColor="#CCCCCC"     
  11.     BorderColor="#999999" BorderStyle="Solid" BorderWidth="3px" CellPadding="4"     
  12.     CellSpacing="2" ForeColor="Black" style="text-align: center">    
  13.     <FooterStyle BackColor="#CCCCCC" />    
  14.     <HeaderStyle BackColor="Black" Font-Bold="True" ForeColor="White" />    
  15.     <PagerStyle BackColor="#CCCCCC" ForeColor="Black" HorizontalAlign="Left" />    
  16.     <RowStyle BackColor="White" />    
  17.     <SelectedRowStyle BackColor="#000099" Font-Bold="True" ForeColor="White" />    
  18.     <SortedAscendingCellStyle BackColor="#F1F1F1" />    
  19.     <SortedAscendingHeaderStyle BackColor="#808080" />    
  20.     <SortedDescendingCellStyle BackColor="#CAC9C9" />    
  21.     <SortedDescendingHeaderStyle BackColor="#383838" />    
  22. </asp:GridView>    
  23. </p>    
  24.     </asp:Content>    
And, here is the code for the code side of the page:
  1. using System;    
  2. using System.Collections.Generic;    
  3. using System.Linq;    
  4. using System.Web;    
  5. using System.Data;    
  6. using System.Web.UI;    
  7. using System.Web.UI.WebControls;    
  8. using System.Data.SqlClient;    
  9. using System.Configuration;    
  10. using System.Text.RegularExpressions;    
  11.    
  12. public partial class Search : System.Web.UI.Page    
  13. {     
  14.     protected void Page_Load(object sender, EventArgs e)    
  15.     {    
  16.         if (!this.IsPostBack)    
  17.         {    
  18.             this.BindGrid();    
  19.         }    
  20.     }    
  21.     
  22.     private void BindGrid()    
  23.     {    
  24.         string constr = ConfigurationManager.ConnectionStrings["regConnectionString"].ConnectionString;    
  25.         using (SqlConnection con = new SqlConnection(constr))    
  26.         {    
  27.             using (SqlCommand cmd = new SqlCommand())    
  28.             {    
  29.                 cmd.CommandText = "SELECT * FROM projects WHERE Company LIKE '%' + @Company + '%'";    
  30.                 cmd.Connection = con;    
  31.                 cmd.Parameters.AddWithValue("@Company", txtSearch.Text.Trim());    
  32.                 DataTable dt = new DataTable();    
  33.                 using (SqlDataAdapter sda = new SqlDataAdapter(cmd))    
  34.                 {    
  35.                     sda.Fill(dt);    
  36.                     GridView1.DataSource = dt;    
  37.                     GridView1.DataBind();    
  38.                 }    
  39.             }    
  40.         }    
  41.     }    
  42.     
  43.     protected void OnPageIndexChanging(object sender, GridViewPageEventArgs e)    
  44.     {    
  45.         GridView1.PageIndex = e.NewPageIndex;    
  46.         this.BindGrid();    
  47.     }    
  48.     protected void Button1_Click(object sender, EventArgs e)    
  49.     {    
  50.         this.BindGrid();    
  51.     }    
  52. }    
Are you really looking for the 8th step? It is all done. Just run your project and enjoy using it.
 
Please don’t hesitate to ask if something went wrong.