Adding the Database

To demonstrate how to delete rows from a database with a grid view, we will need to create a simple web site with a database. For this example we will be creating our own small sample database. To begin, create a new ASP.NET Empty Web Site and:

  1. Right click the project in your solution explorer.
  2. Select Add ASP.NET Folder.
  3. Select App_Data.
  4. Right click the App_Data folder.
  5. Select add new item…
  6. Select a SQL Server Database.
  7. Name it ‘Database.mdf’.
  8. Click add.
  9. Right click the Tables folder.
  10. Select add new table.
  11. Add the following columns with their respective types to the table:
    Data Type Column Name
    ID int
    Data varchar(50)
  12. Set the ID columns to the primary key and identity of the table.
  13. Save the table as ‘Table1′.
  14. Right click Table1.
  15. Select show table data.
  16. Add the following sample data to the table:
    ID Data
    1 test1
    2 test2
    3 test3

Once we have our database setup with some sample data in it that we can delete, we need to add a connection string so that we can connect to our database. To do this open up the Web.Config file for editing and add in the following code:

This simply directs the web site to our database.

Creating the Form

To allow the user to delete items from our database through a grid view, we will need to create a simple web form. To begin:

  1. Right click the project in your solution explorer.
  2. Select add new item…
  3. Select a web form.
  4. Name it ‘Default.aspx’.
  5. Click add.
  6. Open Default.aspx up to design mode.
  7. Drag and drop a sqldatasource onto the web form.
  8. Expand the sqldatasource tasks menu.
  9. Select Configure Data Source…
  10. Select the ‘ConnectionString’ that we added earlier.
  11. Click next.
  12. Select Table1 from the drop down list.
  13. Select all columns from the table.
  14. Click Advanced…
  15. Check Generate INSERT, UPDATE, and DELETE statements.
  16. Click ok.
  17. Click next.
  18. Test the query.
  19. Click finish.

Once we have our SQL data source configured, we need to add our grid view that will actually display our data. To do this, open Default.aspx up to design mode and:

  1. Drag and drop a gridview onto the web form.
  2. Set the DataSourceID property to ‘SqlDataSource1′.
  3. Change the AutoGenerateDeleteButton property to ‘True’.

Testing

To test this out load up the web site. Delete a few entries to ensure that the delete button is calling our delete SQL query from our data source. This demonstrates how you can easily configure a grid view to delete entries from your database without having to write any code.

Download Source Files