Delete record from Datagrid in windows application using c#


In this article we will learn how to delete item from Datagrid in window application using button inside DataGridView.

Follow these steps:

        1.  Add a webform in your application. Now add a datagrid to form.
  2.  No go to column property of Datagrid and click on Collectionto add button.

3.      No Click on Add button to add button.

          4.      Select DataGridViewButtonColumn option from Type drop down and click Add.

  5.      Now you can customize the properties. And click Ok.

Now Button is added to DataGridview


  6.    Now   Fill dataGridView and Write Code to delete record on CellClick event of datagrid:

       Database Table:













Fill DataGridview (C# code to fill DataGridview)  

private void Form3_Load(object sender, EventArgs e)
        {
            FillGrid(); 
        }

private void FillGrid()
        {
            DataTable dt = new System.Data.DataTable();
            SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["con"].ConnectionString);
            con.Open();
            SqlDataAdapter adp = new SqlDataAdapter("Select * from Employee", con);
            adp.Fill(dt);
            dataGridView1.DataSource = dt;
            con.Close();
        }

Now Write Code on CellClick Event of Gridview to Delete record:

private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            //Check Index of Delete Button
            if (e.ColumnIndex == 0)
            {
                //Confirm Do you want to delete this record or not?
                DialogResult dlg = MessageBox.Show("Do you want to delete this item", "Delete", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2);

                if (dlg == DialogResult.Yes)
                {
                    int id = Convert.ToInt16(dataGridView1.Rows[e.RowIndex].Cells["Id"].Value.ToString());
                    SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["con"].ConnectionString);
                    con.Open();
                    SqlCommand cmd = new SqlCommand("delete from Employee where Id=" + id, con);
                    cmd.ExecuteNonQuery();
                    con.Close();
      FillGrid();
                    MessageBox.Show("record Deleted successfully");
                }
            }


        }


EmoticonEmoticon