Whats wrong with my code? I want to remove a row from gridview when I click delete hyperlink(button).
It shows that the value is out of range. What Should i do?
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
cn = new SqlConnection(conStr);
delCmd = new SqlCommand();
cn = new SqlConnection(conStr);
cn.Open();
//delCmd.Connection = cn;
delCmd = new SqlCommand("spDelEmployee",cn);
delCmd.CommandType = CommandType.StoredProcedure;
delCmd.CommandText = "spDelEmployee";
delCmd.Parameters.Add("@EmployeeID", SqlDbType.Int).Value = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Values);
cn.Open();
delCmd.ExecuteNonQuery();
DataBind();
cn.Close();
}
Stored procedure:
ALTER PROCEDURE spDelEmployee
@EmployeeID int
AS
DELETE FROM Employed WHERE EmployeeID=@EmployeeID
RETURN
You can specify a specific cell in a GridView. In your code, you can just replace:
GridView1.DataKeys[e.RowIndex].Values
with:
GridView1.Rows[e.RowIndex].Cells[xxx].Text
where xxx is the 0-indexed column number that contains EmployeeID.
Heres how I solved my problem) It woks.
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
cn = new SqlConnection(conStr);
cn.Open();
delCmd = new SqlCommand("spDelEmployee",cn);
delCmd.CommandType = CommandType.StoredProcedure;
object id = GridView1.Rows[e.RowIndex].Cells[em.EmployeeID].Text.ToString();
delCmd.Parameters.Add("@EmployeeID", SqlDbType.Int).Value = Convert.ToInt32(id);
delCmd.ExecuteNonQuery();
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.