简体   繁体   English

使用存储过程从GridView删除行

[英]Deleting Row From GridView With Stored Procedure

Whats wrong with my code? 我的代码有什么问题? I want to remove a row from gridview when I click delete hyperlink(button). 单击删除超链接(按钮)时,我想从gridview中删除一行。

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. 您可以在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. 其中xxx是0索引的列号,其中包含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();

    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM