Windows Forms: Delete multiple Rows from DataGridView based on CheckBox selection in C#
By FoxLearn 7/25/2017 9:27:44 PM 7.87K
Delete multiple rows from DataGridView based on CheckBox selection in C#
Step 1: Click New Project, then select Visual C# on the left, then Windows and then select Windows Forms Application. Name your project "DeleteSelectedValue" and then click OK
Step 2: Design your form as below
Step 3: Create an Entity Framework Model, then select category table from Northwind database
Step 4: Add code to handle your form as below
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 DeleteSelectedValue { public partial class Form1 : Form { public Form1() { InitializeComponent(); } TestEntities db; private void Form1_Load(object sender, EventArgs e) { //Init data db = new TestEntities(); categoryBindingSource.DataSource = db.Categories.ToList(); } private void btnDelete_Click(object sender, EventArgs e) { //Delete data int total = dataGridView.Rows.Cast<DataGridViewRow>().Where(p => Convert.ToBoolean(p.Cells["Selected"].Value) == true).Count(); if (total > 0) { string message = $"Are you sure want to delete {total} row?"; if (total > 1) message = $"Are you sure want to delete {total} rows"; if (MessageBox.Show(message, "Message", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) { for(int i = dataGridView.RowCount - 1; i >= 0; i--) { DataGridViewRow row = dataGridView.Rows[i]; //Check row selected if (Convert.ToBoolean(row.Cells["Selected"].Value) == true) { db.Categories.Remove((Category)row.DataBoundItem); categoryBindingSource.RemoveAt(row.Index); } } } } } private async void btnSave_Click(object sender, EventArgs e) { //Save data to sql database categoryBindingSource.EndEdit(); await db.SaveChangesAsync(); MessageBox.Show("Your data has been successfully saved.", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information); } } }
VIDEO TUTORIALS
- Windows Forms: Advanced Filter DataGridView in C#
- Windows Forms: Progress Bar in C#
- How to create a Lucky Draw games in C#
- Windows Forms: Youtube Search with Paging in C#
- Windows Forms: How to Create a Random Password Generator in C#
- Windows Forms: Tag Control in C#
- Windows Forms: Wait Form Dialog in C#
- Windows Forms: Text to speech in C#
Categories
Popular Posts
Visual Studio: Auto increment version
03/22/2024
What is ARM architecture?
03/11/2024