C# - How To Remove A Row From DataGridView In C#

C# - How To Delete The Selected Row From DataGridView Using C#


                                                                                                                                                     

In This C# Code We Will See How To Remove The Selected Row From DataGridView 
In C# Programming Language.




Source Code:

 using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Remove_DataGridView_Selected_Row : Form
    {
        public Remove_DataGridView_Selected_Row()
        {
            InitializeComponent();
        }

        DataTable table = new DataTable();

        private void Remove_DataGridView_Selected_Row_Load(object sender, EventArgs e)
        {
     // set datatable columns values
     table.Columns.Add("Id", typeof(int));// data type int
     table.Columns.Add("First Name", typeof(string));// datatype string
     table.Columns.Add("Last Name", typeof(string));// datatype string
     table.Columns.Add("Age", typeof(int));// data type int

            table.Rows.Add(1, "First A", "Last A", 10);
            table.Rows.Add(2, "First B", "Last B", 20);
            table.Rows.Add(3, "First C", "Last C", 30);
            table.Rows.Add(4, "First D", "Last D", 40);
            table.Rows.Add(5, "First E", "Last E", 50);
            table.Rows.Add(6, "First F", "Last F", 60);
            table.Rows.Add(7, "First G", "Last G", 70);
            table.Rows.Add(8, "First H", "Last H", 80);

            dataGridView1.DataSource = table;
        }

        // Remove Selected Row From DataGridView
        private void btnDelete_Click(object sender, EventArgs e)
        {
            //get the index of the selected row in datagridview
            //and delete a row from datatable
            //and bind the datagridview with datatable
            int rowIndex = dataGridView1.CurrentCell.RowIndex;
            dataGridView1.Rows.RemoveAt(rowIndex);

        }
    }
}

//////////////////////// OUTPUT:

C# Remove DataGridView Selected Row
Before Removing

C# Remove DataGridView Selected Row
After Removing


ALSO SEE : 

Add A Row To DataGridView From TextBox
Get Selected Row Values From DataGridView Into TextBox
Update A DataGridView Row With TextBox
Add Delete And Update DataGridView Row Using TextBoxes

Share this

Related Posts

Previous
Next Post »