How to Remove Item in DataGrid View Control in C#

In this tutorial I explain how to remove item in DataGrid view control in C#. Create New Project and give the Name of the project is RemoveItemDataGridView. Add the DataGrid View Control then copy this code and paste.
usingSystem;
usingSystem.Collections.Generic;
usingSystem.ComponentModel;
usingSystem.Data;
usingSystem.Drawing;
using System.Linq;      
usingSystem.Text;
usingSystem.Windows.Forms;
namespaceRemoveItemDataGridView
{
    public partial class Form1 : Form
    {
        publicForm1()
        {
            InitializeComponent();
        }
        privatevoid Form1_Load(objectsender, EventArgs e)
        {
            DataGridV.ColumnCount  =3;
            DataGridV.Columns[0].Name = “Emp_code”;
            DataGridV.Columns[1].Name = “Emp_Name”;
            DataGridV.Columns[2].Name = “Emp_Salary”;
          
            string[] rw = new string[] {“101”,“John”,“15000” };
            DataGridV.Rows.Add(rw);
            string[] rw1 = new string[] {“102”,“Fleming”,“10000” };
            DataGridV.Rows.Add(rw1);
            string[] rw2 = new string[] {“103”,“Steph”,“60000” };
            DataGridV.Rows.Add(rw2);
            string[] rw3 = new string[] {“104”,“Jay”,“50000” };
            DataGridV.Rows.Add(rw3);
            DataGridViewButtonColumn  cmdbtn = new  
            DataGridViewButtonColumn();
           
            cmdbtn.UseColumnTextForButtonValue = true;
            cmdbtn.Text = “Delete”;
          
            DataGridV.Columns.Add(cmdbtn);
           
            
        }
        privatevoid DataGridV_CellContentClick(object sender,   
       DataGridViewCellEventArgse)
        {
            try
            {
                intselectindex = DataGridV.CurrentCell.RowIndex;
                if(selectindex > -1)
                {
                    DataGridV.Rows.RemoveAt(selectindex);
                    DataGridV.Refresh();
                }
                selectindex = -1;
            }
            catch(InvalidOperationException ex)
            {
                MessageBox.Show(“Unable to remove select row”);
            }
        }
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *