How to delete a record from a datagrid

esposito

Centurion
Joined
Jul 11, 2003
Messages
103
Location
Perugia - Italy
Hello, I have a datagrid control bound to an Access database. To populate the datagrid, I use the following code:

Visual Basic:
          Dim mykeyword As String = Replace(txtKeyWord.Text, "'", "''")
          Dim MySQL as string = "Select * from employees WHERE surname = '" & mykeyword & "' Order by id_employee"

          Dim myConn As OleDbConnection = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;" & "Data Source=" & server.mappath("employees.mdb") & ";")
          Dim ds as DataSet=New DataSet()

          Dim Cmd as New OleDbDataAdapter(MySQL,MyConn)
          Cmd.Parameters(0) = myKeyword
          Cmd.Fill(ds,"employees")

          myDataGrid.Datasource=ds.Tables("employees").DefaultView
          myDataGrid.DataBind()
          MyConn.Close()

What I would like to do is add a hyperlink field to the datagrid that will allow me to delete the selected record.

In WebMatrix (the IDE that I use) it is very easy to transform a field into a hyperlink. What I can't do, as I said, is delete the current record when I click on that hyperlink.

I know it is possible because I have seen a datagrid control implementing that function.

Any help will be appreciated.
 
You are right, this can be done. I don't have the code in front of me at the moment so how bout some psuedocode.

You have a click event on your hyperlink button. when the user clicks you know what record they want ousted. You then need to use that info to get that single record from your table. You are going to need a primary key or some way to single this record out form the others. Then you use that key to build some SQL like
"Delete from myTable Where ID = " & myPK

Where myPK is what uniquely identifies your rec.

Don't know if that helps you much or if you knew all that already.
This is sort of the 'manual' way to go about this process. I have only been using ADO.NET for about a year so I do it this way. There is a better way to do this using the data application block. .NET is smart enough to create these delete and insert statements for you if you use VS.Studio and the lizards to setup your datagrid.
 
Back
Top