Gridview Delete Operation
For Complete gridview design please follow earlier code about gridview edit operation here.
Only we add following in gridview design
AutoGenerateDeleteButton="True" OnRowDeleting="gridData_RowDeleting"
Stored Procedure for Delete Operation
CREATE PROCEDURE SP_Delete_User
-- Add the parameters for the stored procedure here
@userID int
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
--1. REMOVE RECORDS FROM DEPENDANT TABLE
DELETE FROM [dbo].[User_In_Org_Role]
WHERE User_ID = @userID
--2. REMOVE RECORD FROM ACTUAL TABLE
DELETE FROM [dbo].[User]
WHERE User_ID=@userID
END
GO
Note: In stored procedure above, we perform delete operation on [User_In_Org_Role] table first because it has foreign key reference to table [User].
Here is code for delete operation :
1. Confirm delete operation
protected void gridData_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
Try
{
LinkButton lbDelete = (LinkButton)e.Row.Cells[0].Controls[2];
if (lbDelete.Text.Trim().Equals("Delete"))
{
lbDelete.OnClientClick = "return confirm('confirm delete
action?');";
}
}
catch (Exception)
{
// throw
}
}
}
2. Delete Event
protected void gridData_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
if (e.RowIndex != -1 && gridData.Rows[e.RowIndex].RowType ==
DataControlRowType.DataRow)
{
try
{
//1. get PKey field value
Label lblDataUser_ID = (Label)gridData.Rows[e.RowIndex].FindControl("lblDataUser_ID");
int User_ID = Convert.ToInt32(lblDataUser_ID.Text);
//method to delete
clsConnect cc = new clsConnect();
cc.DeleteData(User_ID);
}
catch (Exception)
{}
}
gridData.EditIndex = -1;
GetDt();
}
Note : For GetDt() details follow details in Gridview Edit Post
3. Method to execute Stored Procedure
public void DeleteData(int UserID)
{
//SP_Delete_User
//@userID int
SqlConnection con = new SqlConnection(connectionString);
con.Open();
try
{
SqlCommand cmd = new SqlCommand("SP_Delete_User", con);
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter spuserID = new SqlParameter();
spuserID.ParameterName = "@userID";
spuserID.DbType = DbType.Int32;
spuserID.Value = UserID;
cmd.Parameters.Add(spuserID);
cmd.ExecuteNonQuery();
}
catch (Exception)
{
}
con.Close();
}
No comments:
Post a Comment