2

How to delete a gridview line on the click button after the check box of the row...

 3 years ago
source link: https://www.codesd.com/item/how-to-delete-a-gridview-line-on-the-click-button-after-the-check-box-of-the-row-is-selected.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

How to delete a gridview line on the click button after the check box of the row is selected

advertisements

I have a DataGridView created in C# windows forms and checkboxColumn added to it. The DataGridView is populated with other columns like Sno, AccountNo, Name, Salary (Sno is identitycolumn and primarykey).

I want to delete a row (using stored procedure) by selecting the checkbox and on button click which is out side DataGridView. Error at "FindControl".

Stored Procedure:

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


Let say this is your stored procedure:

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

    RETURN

You don't need a StringCollection to delete or call the stored procedure.

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

Please let me know if you have some encountered problem from my given answer.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK