How to delete rows from DataGrid in ASP.NET ?

Apr 21 2015 1:47 AM
 Hi . I have an employee table with fields Employee Id, Employee Name, Address,Salary , Department ID and department table with fields DeptID,DeptName.
I have added a data grid control with the columns showing Empname , address , salary,DeptName and Edit and Delete columns .
I have inserted image using template columns in the Edit and Delete column .
By clicking on the image in delete column , it should delete that particular row from the datagrid and from database and on refreshing the grid the changes should be shown in the datagrid .
I have written the following code  :  
 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using System.Data.SqlClient;
using System.Data;
public partial class Default2 : System.Web.UI.Page
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
FillDataGrid();
}
}
public void FillDataGrid()
{
String strConnString = ConfigurationManager.ConnectionStrings["Company"].ConnectionString;
SqlConnection con = new SqlConnection(strConnString);
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "proc_Getallempdetails";
cmd.Connection = con;
try
{
con.Open();
DataGrid1.DataSource = cmd.ExecuteReader();
DataGrid1.DataBind(); } 
catch (Exception ex)
{
throw ex;
}
finally
{
con.Close();
con.Dispose();
}
}
protected void DataGrid1_DeleteCommand(object source, DataGridCommandEventArgs e)
{ String strConnString = ConfigurationManager.ConnectionStrings["Company"].ConnectionString ;
SqlConnection con = new SqlConnection(strConnString);
SqlCommand cmd = new SqlCommand();
cmd = new SqlCommand("Delete from Emp where Empid=" + DataGrid1.DataKeys[e.Item.ItemIndex].ToString(), con);
con.Open();
int rows = cmd.ExecuteNonQuery();
if (rows > 0)
{
Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "Deleted", "<script>alert('Deleted Successfully')</script>");
con.Close();
FillDataGrid();
}
}
 I m able to get the data in the datagrid but delete is not taking place. Please help .  
 
 

Answers (3)