如何从gridview中删除行,在选中row's复选框后单击按钮

本文关键字:复选框 单击 按钮 gridview 删除行 row | 更新日期: 2023-09-27 17:54:02

我有一个DataGridView创建在c# windows窗体和checkboxColumn添加到它。DataGridView由其他列填充,如Sno, AccountNo, Name, Salary (Sno是identitycolumn和primarykey)

我想删除一行(使用存储过程)通过选择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();
        }
    }

如何从gridview中删除行,在选中row's复选框后单击按钮

假设这是您的存储过程:

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();
                        }
                    }
                }
            }
        }
    }

如果你有什么问题,请告诉我。

试试这个解决方案。在我的代码中,我有类,并通过它的gridview列表作为我的数据源。

<<p> //类/strong>
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
            }
        }