In this example, I’ll show How To Delete The Selected DataGridView Row In C#.
RemoveAt Method: When you remove an item from the list, the indexes change for subsequent items in the list. All information about the removed item is deleted. You can use this method to remove a specific item from the list by specifying the index of the item to remove from the list.
Output:
Form Design:
Source Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 | 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 remove_datagrid { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect; DataTable table = new DataTable(); table.Columns.Add("Id", typeof(int)); table.Columns.Add("Book", typeof(string)); table.Columns.Add("Borrowed Date", typeof(DateTime)); table.Columns.Add("Delivered Date", typeof(DateTime)); table.Rows.Add(1, "Book A", "15.01.2018", "30.06.2019"); table.Rows.Add(2, "Book B", "05.03.2018", "28.11.2018"); table.Rows.Add(3, "Book C", "10.11.2018", "03.07.2018"); table.Rows.Add(4, "Book D", "17.02.2018", "12.03.2018"); table.Rows.Add(5, "Book E", "07.01.2018", "15.01.2018"); table.Rows.Add(6, "Book F", "18.04.2018", "10.05.2018"); table.Rows.Add(7, "Book G", "30.01.2018", "05.03.2018"); table.Rows.Add(8, "Book H", "22.05.2018", "20.06.2018"); dataGridView1.DataSource = table; } private void button1_Click(object sender, EventArgs e) { int selectedIndex = dataGridView1.CurrentCell.RowIndex; if (selectedIndex > -1) { dataGridView1.Rows.RemoveAt(selectedIndex); dataGridView1.Refresh(); } } } } |