Understanding Row State

Deleting a Row from DataGridView and inserting it to another Grid.

Create a Window Form Application Project:-

Having a form with two DataGridViews “DataGridView1' and “DataGridView2”

Bind Gridview With Programmatic Binding as

Include name Space:- using System.Data.SqlClient;

Bind data at page load event

SqlDataAdapter da;

DataSet ds;

DataTable dt;

private void Form1_Load(object sender, EventArgs e)

{

da = new SqlDataAdapter("Select * from emp", "initial catalog=mine;data source=.;integrated security=true");

ds = new DataSet();

da.Fill(ds, "Emp");

dataGridView1.DataSource = ds.Tables["Emp"];

dt = ds.Tables[0].Clone(); //This method copy only schema of table

dataGridView2.DataSource = dt; //Appling data source to second Grid view (Table that containing the schema of “ds.Tables[0]”

}

Generate event to create method for Deleting a Row in DataGridView to do that Right click on Grid View and click on property in popup menu

Click on event symbol from property menu

Double click on event userDeletingRow to auto generated method it will create a method

and write the following code in that event

private void dataGridView1_UserDeletingRow(object sender, DataGridViewRowCancelEventArgs e)

{

//This event fires when a row is deleted by user

//(To do that click on row header to select the row and press Delete Key from keyboard

dt.ImportRow(ds.Tables[0].Rows[e.Row.Index]); //Import Row in dt(data table) Source of second DataGridView

ds.Tables[0].AcceptChanges(); //Row is in the deleted state this method confirm the deletion

dt.RejectChanges(); //Row in the dt is also in deleted state so do not appear so we call reject changes to

// Reject the row state from deleting to normal

}

Row will shift from GridView1 to Grid View 2

Click on Row header to select the Row then press “Delete” key to delete the Row

This will Remove Row from DataGridView1 and Insert into DataGridView2