Saturday 10 November 2012

How to delete the selected Rows from dataGridView in C#.net

Here we discuss about How to delete the selected Rows from dataGridView,Most of the times our operations are doing from dataGridview
only,we performed Save,Delete,Search etc.Like that here we discuss about Delete Selected rows from dataGridView for that we gave the code for that and screenshots given below.



Code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace Blogcode
{
    public partial class dgvSlctRwsDel : Form
    {
        public dgvSlctRwsDel()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            foreach (DataGridViewRow row in dataGridView1.SelectedRows)
              {
                 if (!row.IsNewRow)
                    {
                    dataGridView1.Rows.Remove(row);
                    }
                    MessageBox.Show("Selected rows Deleted");
             }
        }
    }
}

This code only for dataGridView selected rows only not for DataTable (or) DataBase,If you want to Delete in DataTable and also Database
we need to "update"these dataGridView after perform Delete operation for that we use "commandBuilder"object to update the Database.


I hope this code will help you.