Search This Blog

Friday, April 2, 2010

Delete Selected Row in GridView Control

This Example show you how to delete selected row from gridview control in your windows form application.
In this example i used Ms-Access as data base.this is devoted for how to select the row and then delete it from database;this is simple design of page containing a DataGridView And delete Button on it;
This is coding file of this form:

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;
using System.Data.OleDb;
namespace WindowsFormsApplication3
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
OleDbConnection con=new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=d:\WindowsFormsApplication3\WindowsFormsApplication3\db1.mdb;Persist Security Info=True");
OleDbDataAdapter da;
DataSet ds;
private void Form1_Load(object sender, EventArgs e)
{
Bind();
}
private void button1_Click(object sender, EventArgs e)
{
DataGridViewRow dr = dataGridView1.CurrentRow;
string empcode=dr.Cells[0].Value.ToString();
OleDbCommand cmd = new OleDbCommand("delete from emp where emp_code='" + empcode + "'", con);
da = new OleDbDataAdapter();
da.DeleteCommand = cmd;
ds.Tables[0].Rows[dr.Index].Delete();
da.Update(ds);
Bind();
}
void Bind()
{
ds = new DataSet();
ds.Clear();
da = new OleDbDataAdapter("select * from emp", con);
da.Fill(ds);
dataGridView1.DataSource = ds.Tables[0];
}
}
}
Above i created a function named Bind() to Load the data from database bcoz after deleting the row calling this function will update the DataGridView and populate the updated database.

No comments:

Post a Comment