Wednesday, December 02, 2009

Gridview row deleting in C#

Steps to delete a row in Grid view programmatic which bind with real time database table.
1,In Grid view server control must be set to false of AutoGenerateColumns
2,Make Columns tag to list the user defined column header on the asp.net page.
just like the following
  
DataKeyNames="ProductID" SelectedIndex="1"
onselectedindexchanged="GridView1_SelectedIndexChanged"
onrowcommand="GridView1_RowCommand" AutoGenerateColumns="false">








3,Set to DataKeyNames value to Table's primary key like
  
DataKeyNames="ProductID" SelectedIndex="1"
onselectedindexchanged="GridView1_SelectedIndexChanged"
onrowcommand="GridView1_RowCommand" AutoGenerateColumns="false">


An event named "onrowcommand" triggered on the Grid view deletion of the selected row must be deleted from the table.

Here I used the filter CommandName and commandArgument to check whether the deletion link button which attached the GridView clicked.


protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Remove")
{
int index = Convert.ToInt32(e.CommandArgument);
GridViewRow row = GridView1.Rows[index];

Database db = DatabaseFactory.CreateDatabase("DatabaseConnectionString");
DbCommand cmd = db.GetSqlStringCommand("DELETE from Products where ProductID='" + row.Cells[1].Text.ToString() + "'");
db.ExecuteNonQuery(cmd);
GridView1.DataSource = ShowProductDetail();
GridView1.DataBind();

}

}


I used Microsoft Enterprise Library 4.1 in my example to deal with database and its related operation.Its based on SQLExpress database.