ASP.Net C# Gridview Delete Not Deleting When Using SQLDataSource

July 14, 2011

Normally the ASP.Net Gridview control handles the delete of a row just fine. However when you have to delete a row from a table with no primary key the delete will not work if you are using a sqldatasource. After a little research I found an answer.

So after figuring out that the problem is not with the Gridview control. I took a look at the database. It seems that the SQLDataSource reliesĀ on the primary key for deletions. Not sure why but that’s the way it works.

So after thinking on how to get around the limitation. I saw that the Gridview Control has a OnRowDeleting event. From there I added OnRowDeleting to the GridView.


Now in the Code Behind I had to add the function to handle the event. In the function I got the row from the GridView then the text from the cell in the row that had the data. After that I set the delete sql, the type and finally had the SQLDataSource run the delete command.

protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
// get the row in question
GridViewRow row = GridView1.Rows[e.RowIndex];
// get the cell data
string id = row.Cells[1].Text;
//test.Text += pem_ida + ” – HI “;

// set the sql command, type and run the command
SqlDataSource1.DeleteCommand = “DELETE FROM [foo] WHERE [bar] = “+ id;
SqlDataSource1.DeleteCommandType = SqlDataSourceCommandType.Text;

Obviously you need to change GridView1 to your GridView and also SQLDataSource1 to your SQLDataSource. Also row.Cells[1].Text needs to be the number where your data is.

Got something to say?

You must be logged in to post a comment.