In this programming tutorial we will learn how to update records in database using 3-tier architecture in asp.net with c#. For beginners, I strongly recommend to read this tutorial 3-Tier Architecture in asp.net using c# first to get basics of three tier architecture in asp.net. So let’s begin, have a look over .aspx page
Update records using three tier architecture in asp.net with c#.
view-users.aspx
view-users.aspx.cs
edit-users.aspx.cs
Every thing is self explanatory and I will not go into further details as I already have written three tutorials 3-Tier Architecture in asp.net using c# , Insertion of records in database using 3-tier architecture in asp.net with c#,Delete records in database using 3-tier architecture in asp.net with c#. In case you have any confusion in BusUsers then read the comments in it or read the above mentioned tutorials to get the basics. So this is the way to update records in database using three tier architecture in asp.net with c#.
So that's it.
I love your feedback.
view-users.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="view-users.aspx.cs" Inherits="view_users" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title> Update records in database using 3-tier architecture in asp.net with c#</title> </head> <body> <form id="form1" runat="server"> <asp:GridView ID="GridView1" runat="server" EnableTheming="false" AutoGenerateColumns="false" GridLines="None" Width="100%" OnRowEditing="GridView1_RowEditing"> <Columns> <asp:TemplateField HeaderText="First Name" HeaderStyle-Width="20%" HeaderStyle-HorizontalAlign="Left"> <ItemTemplate> <asp:Label ID="lblFirstName" runat="server" EnableTheming="false" Text='<%# Bind("FirstName")%>'></asp:Label> </ItemTemplate> <ItemStyle HorizontalAlign="Left" /> </asp:TemplateField> <asp:TemplateField HeaderText="Last Name" HeaderStyle-Width="20%" HeaderStyle-HorizontalAlign="Left"> <ItemTemplate> <asp:Label ID="lblLastName" runat="server" EnableTheming="false" Text='<%# Bind("LastName")%>'></asp:Label> </ItemTemplate> <ItemStyle HorizontalAlign="Left" /> </asp:TemplateField> <asp:TemplateField HeaderText="Country" HeaderStyle-Width="20%" HeaderStyle-HorizontalAlign="Left"> <ItemTemplate> <asp:Label ID="lblCountry" runat="server" EnableTheming="false" Text='<%# Bind("Country")%>'></asp:Label> </ItemTemplate> <ItemStyle HorizontalAlign="Left" /> </asp:TemplateField> <asp:TemplateField HeaderText="Age" HeaderStyle-Width="20%" HeaderStyle-HorizontalAlign="Left"> <ItemTemplate> <asp:Label ID="lblAge" runat="server" EnableTheming="false" Text='<%# Bind("Age")%>'></asp:Label> </ItemTemplate> <ItemStyle HorizontalAlign="Left" /> </asp:TemplateField> <asp:TemplateField HeaderText="Edit" HeaderStyle-Width="15%" HeaderStyle-HorizontalAlign="Center"> <ItemTemplate> <asp:Label ID="lblEdit" Visible="false" Text='<%# Bind("Id")%>' runat="server"></asp:Label> <asp:ImageButton runat="server" ID="img_edit" ImageUrl="images/edit.gif" CommandName="Edit" /> </ItemTemplate> <ItemStyle HorizontalAlign="Center" /> </asp:TemplateField> </Columns> </asp:GridView> <br /> <div style="text-align: center;"> <asp:Button ID="btnBack" runat="server" Style="font-size: 12px;" Text="Back" OnClientClick="history.back(-1); return false;" /> </div> </form> </body> </html>As you have seen, we have an asp:gridview control in our web page. We have five template fields in it; these are FirstName, LastName, Country, Age and Edit image to update the records. The main things you must have to notice are the OnRowEditing event of gridview and label lblEdit that contains the primary key for updation of records, in this example lblEdit contains the value of Id column of users table. Through OnRowEditing event we will update the records in database. So let’s have a look over its c# code behind file.
view-users.aspx.cs
using System; using System.Collections; using System.Configuration; using System.Data; using System.Linq; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Xml.Linq; using BusinessLayer; //Don’t forget to include this namespace public partial class view_users : System.Web.UI.Page { BusUsers _objUsers = new BusUsers(); protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { //Binding gridview with records coming from database. BindGrid(); } } public void BindGrid() { _objUsers.GetUsersRecords(); // The table userrecords is a dynamically created table that we have // created in the BusUsers class. Userrecords table contains all the //records comes from database. GridView1.DataSource = _objUsers.UserDS.Tables["userrecords"]; GridView1.DataBind(); } #region Editing protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e) { //Getting index of currently selected row int index = e.NewEditIndex; GridViewRow row = GridView1.Rows[index]; //The asp:Label just before the edit image button Label lbl = (Label)row.FindControl("lblEdit"); int id = Convert.ToInt32(lbl.Text); // redirecting to next page with query string that will always contain a unique value Response.Redirect("edit-users.aspx?id=" + id + ""); } #endregion }edit-users.aspx
<table width="100%" cellpadding="2" cellspacing="2" border="0" align="left"> <tr id="trMessage" runat="server" visible="false"> <td style="color: Green;" colspan="2"><strong>The record has been updated successfully. </strong> </td> </tr> <tr> <td width="15%" align="left" ><strong>FirstName</strong></td> <td align="left"> <asp:TextBox ID="txtFirstName" runat="server" Font-Size="Small" Width="150px"></asp:TextBox> </td> </tr> <tr> <td align="left"><strong>Last Name</strong></td> <td align="left"><asp:TextBox ID="txtLastName" runat="server" Font-Size="Small" Width="150px"></asp:TextBox> </td> </tr> <tr> <td align="left"><strong>Country</strong> </td> <td align="left"><asp:TextBox ID="txtCountry" runat="server" Font-Size="Small" Width="150px"></asp:TextBox> </td> </tr> <tr> <td align="left"><strong>Age</strong> </td> <td align="left"><asp:TextBox ID="txtAge" runat="server" size="5" Font-Size="Small"></asp:TextBox> </td> </tr> <tr> <td> </td> <td align="left"><asp:Button ID="btnUpdate" runat="server" Text="Update" OnClick="btnUpdate_Click"/> <asp:Button ID="btnHistory" runat="server" Text="Back" OnClientClick="history.back(-1); return false;" /> </td> </tr> </table>As you have seen we have four asp:TextBoxes in our page. The txtFirstName will contain the value of column FirstName in it, the txtLastName will contain the value of column LastName in it, the txtCountry will contain the value of column Country in it, and the txtAge will contain the value of column Age in it. We have also a hidden row, having id of trMessage in our page that will display the successful updating records message once every thing will go fine. Let’s have a look over its code behind file to know how these textboxes will contain values that will come from database and how all the records are updated when we will press the Update button available in our page.
edit-users.aspx.cs
using System; using System.Collections; using System.Configuration; using System.Data; using System.Linq; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Xml.Linq; using BusinessLayer; //Don’t forget to declare this public partial class edit_users : System.Web.UI.Page { BusUsers _objUsers = new BusUsers(); //Declare global variable id int id; protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { id = Convert.ToInt32(Request.QueryString["id"]); //Getting records of users from database against id that we got from query string _objUsers.GetSelectedUserInfo(id); //[0] [0] means first column of first row return by query, which is FirstName // the first [0] indicated the row number, in this example we will have just one row //So we will always use the [0] for row number but column number will change respectively. txtFirstName.Text = _objUsers.UserDS.Tables["selected_user_info"].Rows[0][0].ToString(); txtLastName.Text = _objUsers.UserDS.Tables["selected_user_info"].Rows[0][1].ToString(); txtCountry.Text = _objUsers.UserDS.Tables["selected_user_info"].Rows[0][2].ToString(); txtAge.Text = _objUsers.UserDS.Tables["selected_user_info"].Rows[0][3].ToString(); } } protected void btnUpdate_Click(object sender, EventArgs e) { id = Convert.ToInt32(Request.QueryString["id"]); // Calling function to update records in database _objUsers.UpdateUsers(id, txtFirstName.Text, txtLastName.Text, txtCountry.Text,Convert.ToInt32(txtAge.Text)); // Show the successful message trMessage.Visible = true; // Redirects to the page after 5 seconds delay. Response.AddHeader("REFRESH", "5;URL=view-users.aspx"); } }BusUsers.cs
using System; using System.Collections.Generic; using System.Text; using System.Data; using DataAccessLayer; //Don’t forget to import this namespace namespace BusinessLayer { public class BusUsers { DbAccess _dbAccess = new DbAccess(); private DataSet _UserDS = new DataSet(); public DataSet UserDS { get { return _UserDS; } set { _UserDS = value; } } public void GetUsersRecords() { try { string strQuery = "select FirstName,LastName,Country,Age,id from web_tbl_users"; if (_UserDS.Tables.Contains("userrecords")) { _UserDS.Tables["studentrecords"].Clear(); } _dbAccess.selectQuery(_UserDS, strQuery, "userrecords"); } catch (Exception ex) { throw ex; } } //Function to get user records from database, in this example I used MS SQL SERVER as a backend database public void GetSelectedUserInfo(int id) { try { string strGet = "select FirstName,LastName,Country,Age from web_tbl_users where id=" + id + ""; if (_UserDS.Tables.Contains("selected_user_info")) { _UserDS.Tables["selected_user_info"].Clear(); } _dbAccess.selectQuery(_UserDS, strGet, "selected_user_info"); } catch (Exception ex) { throw ex; } } //Function to get update records from database, in this example I used MS SQL SERVER as a backend database public void UpdateUsers(int id, string firstName, string lastName, string country,int age) { try { string updateStrQuery = "update web_tbl_users set FirstName='" + firstName + "', LastName='" + lastName + "', Country='" + country + "', Age='" + age + "' where id='" + id + "'"; _dbAccess.executeQuery(updateStrQuery); } catch (Exception ex) { throw ex; } } } }As far as DbAccess class is concerned, it is available in 3-Tier Architecture in asp.net using c#. DbAccess class is a single class that whole website uses to get connected with database. But we have multiple classes (Buses) in our BusinessLayer namespace (physically in BusinessLayer folder) depends upon our requirements.
Every thing is self explanatory and I will not go into further details as I already have written three tutorials 3-Tier Architecture in asp.net using c# , Insertion of records in database using 3-tier architecture in asp.net with c#,Delete records in database using 3-tier architecture in asp.net with c#. In case you have any confusion in BusUsers then read the comments in it or read the above mentioned tutorials to get the basics. So this is the way to update records in database using three tier architecture in asp.net with c#.
So that's it.
I love your feedback.
0 comments:
Post a Comment