在选中行的复选框后,如何在按钮单击时从gridview中删除行

时间:2013-01-16 13:41:56

标签: c# winforms stored-procedures datagridview

我在C#窗体中创建了DataGridView,并添加了checkboxColumnDataGridView填充了其他列,例如SnoAccountNoNameSalary Sno是identitycolumn和primarykey)< / em>的。

我想删除一行(使用存储过程),方法是选择checkbox并点击按钮DataGridView。 “FindControl”出错。

存储过程:

   Create Procedure uspDeleteSelectedRow
   As
       Delete from EmpDetails where Sno=Sno
   Go 

    private void btnDelete_Click(object sender, EventArgs e)
    {
        //Create String Collection to store IDs of 
        //records to be deleted 
            StringCollection idCollection = new StringCollection();
            string strID = string.Empty;

        //Loop through GridView rows to find checked rows 
        for (int i = 0; i < dataGridView1.Rows.Count; i++)
        {
             CheckBox chkDelete = (CheckBox)dataGridView1.Rows[i].
                    Cells[0].FindControl("chkSelect");
            if (chkDelete != null)
            {
                if (chkDelete.Checked)
                {
                    strID = dataGridView1.Rows[i].Cells[1].ToString();
                    idCollection.Add(strID);
                }
            }
        }
        if (idCollection.Count > 0)
        {
        //Call the method to Delete records 
        DeleteMultipleRecords(idCollection);

        // rebind the GridView
        dataGridView1.DataBind();   
        }
        else
        {
            lblMessage.Text = "Please select any row to delete";
        }

    }

    private void DeleteMultipleRecords(StringCollection idCollection)
    {
        //Create sql Connection and Sql Command
        SqlConnection con = new SqlConnection(Helper.ConnectionString);
        SqlCommand cmd = new SqlCommand();
        string IDs = "";

        foreach (string id in idCollection)
        {
            IDs += id.ToString() + ",";
        }

        try
        {
            string test = IDs.Substring
                          (0, IDs.LastIndexOf(","));
            string sql = "Delete from EmpDetails" + " WHERE ID in (" + test + ")";
            cmd.CommandType = CommandType.Text;
            cmd.CommandText = sql;
            cmd.Connection = con;
            con.Open();
            cmd.ExecuteNonQuery();
        }
        catch (SqlException ex)
        {
            string errorMsg = "Error in Deletion";
            errorMsg += ex.Message;
            throw new Exception(errorMsg);
        }
        finally
        {
            con.Close();
        }
    }

2 个答案:

答案 0 :(得分:2)

假设这是您的存储过程:

ALTER PROCEDURE [dbo].[sp_ToDeleteEmpDetails] @Sno int
    /*
    (
    @parameter1 int = 5,
    @parameter2 datatype OUTPUT
    )
    */
AS
    DELETE FROM EmpDetails 
    WHERE Sno = Sno 

    RETURN

您不需要StringCollection来删除或调用存储过程。

private void btnDelete_Click(object sender, EventArgs e)
{
        foreach (DataGridViewRow item in dataGridView1.Rows)
        {
            bool IsBool = false;

            if (bool.TryParse(item.Cells[1].EditedFormattedValue.ToString(), out IsBool)) //<--Where: The ColumnIndex of the DataGridViewCheckBoxCell
            {
                using (SqlConnection con = new SqlConnection(Helper.ConnectionString))
                {
                    using (SqlCommand cmd = new SqlCommand("sp_ToDeleteEmpDetails", con))
                    {
                        try {
                            cmd.CommandType = CommandType.StoredProcedure;
                            cmd.Parameters.Add("@sno", SqlDbType.Int).Value = item.Cells[0].EditedFormattedValue.ToString(); //<--Where: The ColumnIndex of the Primary key from your DataGridView
                            dataGridView1.Rows.RemoveAt(item.Cells[0].RowIndex);
                            con.Open();
                            cmd.ExecuteNonQuery();
                        } catch (Exception) {

                            throw;
                        }
                        finally
                        {
                            con.Close();
                        }
                    }
                }
            }
        }
    }

如果您在给出的答案中遇到问题,请告诉我。

答案 1 :(得分:1)

试试这个解决方案。在我的代码中,我有一个类,并将它的列表传递给gridview作为我的数据源。

<强> //类

public class User
{
    public bool Selected { get; set; }
    public string UserName { get; set; }
}

//创建列表并绑定到数据网格视图

  private void Form1_Load(object sender, EventArgs e)
    {
        var users = new List<User> { new User { UserName = "Jobert", Selected = false }, new User { UserName = "John", Selected = true }, new User { UserName = "Leah", Selected = true }, new User { UserName = "Anna", Selected = false } };
        dataGridView1.DataSource = users;
    }

//删除时

 private void btnDelete_Click(object sender, EventArgs e)
        {
            //get data back from the source
            var source = dataGridView1.DataSource as List<User>;
            var selectedItems = source.Where(x => x.Selected).ToList();
            foreach (var item in selectedItems)
            {
                //perform the delete
            }

        }