0

DataGridView在 C# windows 窗体中创建并checkboxColumn添加到它。DataGridView填充有其他列,如, Sno, AccountNo, Name(Salary Snoidentitycolumn 和 primarykey)

我想通过选择and on button click which is out side来删除一行(使用存储过程)。“查找控件”出错。checkboxDataGridView

存储过程:

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

2 回答 2

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

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

于 2013-01-18T06:02:35.680 回答
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
            }

        }
于 2013-01-18T04:18:48.090 回答