In this example, we’ll learn how to programatically delete multiple selected rows from a datagridview with Remove Method.
Step 1: Add a button and datagridview to Form.
Step 2: Go to the properties window by clicking on the dataGridView control. Change the SelectionMode to FullRowSelect property of the dataGridView control or add the following code to Form_Load event.
1 2 3 | dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect; |
Step 3: Add code in Form_Load event
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | 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; } |
Step 4: Add Code in Button1_Click
1 2 3 4 5 6 7 8 9 | private void button1_Click(object sender, EventArgs e) { foreach (DataGridViewRow row in dataGridView1.SelectedRows) { dataGridView1.Rows.Remove(row); } } |
Thanks for a good example. more DataGridView please!