How to delete 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#

delete-records.aspx

As you have seen, we have an asp:gridview control in our web page. We have four template fields in it, these are rollNo, firstName, lastName and Delete image to delete the records. The main thing you must have to notice is the OnRowDeleting event of gridview. Through this event we will delete the records from database. So let’s have a look over its c# code behind file.

delete-records.aspx.cs

using System;
using System.Collections;
using System.Configuration;
using System.Data;
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 BusinessLayer;//Don’t forget to include this namespace

public partial class delete_records : System.Web.UI.Page
{
BusStudent _objStudent = new BusStudent();

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

BindGrid();

}

}

public void BindGrid()
{
_objStudent.GetStudentRecords();
GridView1.DataSource = _objStudent.StudentDS.Tables["studentrecords"];
GridView1.DataBind();
}

protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
int index = e.RowIndex;
GridViewRow row = GridView1.Rows[index];
//The asp:label just before delete image
Label lbl = (Label)row.FindControl("lblDelete");
int rollNo = Convert.ToInt32(lbl.Text);
//Deleting Records From Database
_objStudent.DeleteStudentRows(rollNo);
//Again Populating Gridview after records deletion
BindGrid();
}
}

BusStudent.cs

using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using DataAccessLayer;//Donot forget to import this namespace

namespace BusinessLayer
{
public class BusStudent
{
DbAccess _dbAccess = new DbAccess();
private DataSet _StudentDS = new DataSet();
public DataSet StudentDS
{
get
{
return _StudentDS;
}
set
{
_StudentDS = value;
}
}

public void GetStudentRecords()
{

try
{
string strQuery = "select rollNo,firstName,lastName,gender from web_tbl_student";
if (_StudentDS.Tables.Contains("studentrecords"))
{
_StudentDS.Tables["studentrecords"].Clear();
}
_dbAccess.selectQuery(_StudentDS, strQuery, "studentrecords");
}
catch (Exception ex)
{
throw ex;
}

}

//Function to delete records from database, in this example I used MS SQL SERVER as a backend database

public void DeleteStudentRows(int rollNo)
{
try
{
// I will always recommend you to not delete the records physically
string strQuery = "delete from web_tbl_student where rollNo='"+ rollNo +"'";
_dbAccess.executeQuery(strQuery);
}
catch (Exception ex)
{
throw ex;
}

}



}

}

0 comments:

Post a Comment