: hi,
: i doing a project in vb.net using sqlserver i want to delete a row in the data base during run time
----------------------------------------------------------------------
Hi,
See the following Microsoft example.>>
Deleting Data in a SQL Database.
See Also:-
Accessing Data with ASP.NET | Accessing Data with ADO.NET | System.Web.UI.WebControls Namespace | DataGrid Class
Language
Visual Basic
Show All
The following code example presents a page with a column on the left side of the DataGrid that contains a link titled Delete Author in each row. Clicking on the link deletes that row of data from the database.
To see a similar example executed, run the DataGrid10.aspx sample in the ASP.NET QuickStart.
[Visual Basic]
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SqlClient" %>
<html>
<script language="VB" runat="server">
Dim myConnection As SqlConnection
Sub Page_Load(Src As Object, E As EventArgs)
' Create a connection to the "pubs" SQL database located on
' the local computer.
myConnection = New SqlConnection ("server=localhost;" _
& "database=pubs;Trusted_Connection=Yes")
' Determine whether the page is a postback. If it is not a
' postback, call BindGrid.
if Not IsPostBack Then
BindGrid()
End If
End Sub
' When the Delete Author link is clicked, set up a SQL DELETE
' statement, connect to the database, delete the indicated row, and
' rebind the DataGrid to display the updated database.
Sub MyDataGrid_Delete(sender As Object, E As DataGridCommandEventArgs)
Dim deleteCmd As String = "DELETE FROM Authors WHERE au_id = @Id;"
Dim myCommand As SqlCommand = New SqlCommand(deleteCmd, _
myConnection)
myCommand.Parameters.Add(New SqlParameter("@Id", _
SqlDbType.VarChar, 11))
' Initialize the SqlCommand "@Id" parameter to the ID of the row
' that was clicked.
myCommand.Parameters("@Id").Value = _
MyDataGrid.DataKeys(CInt(E.Item.ItemIndex))
' Connect to the database and delete the specified row.
myCommand.Connection.Open()
' Test whether the delete was accomplished, and display the
' appropriate message to the user.
Try
myCommand.ExecuteNonQuery()
Message.InnerHtml = "<b>Record Deleted</b><br>"
Catch ex As SqlException
Message.InnerHtml = "ERROR: Could not delete record"
Message.Style("color") = "red"
End Try
' Close the connection.
myCommand.Connection.Close()
' Rebind the DataGrid to show the updated information.
BindGrid()
End Sub
' The BindGrid procedure connects to the database and implements
' a SQL SELECT query to get all the data in "Authors" table.
public Sub BindGrid()
Dim myCommand As SqlDataAdapter = New SqlDataAdapter("SELECT *" _
& " FROM authors", myConnection)
Dim ds As DataSet = New DataSet()
myCommand.Fill(ds)
MyDataGrid.DataSource=ds
MyDataGrid.DataBind()
End Sub
Regards,
Dr M.