Deleting Rows From DataGrid
Last Modified On : 30-Sep-2006
<!-- The following form displays rows in datagrid along with a checkbox in each row.
Rows can be deleted by turning the checkbox on and then clicking on Delte button --!>
<%@ Page Language="VB" %>
<%@ import Namespace="System.Data,system.Data.SqlClient" %>
<script runat="server">
Dim ConnectionString As String = "uid=sa;database=pubs"
Sub Page_Load(Sender As Object, E As EventArgs)
If Not Page.IsPostBack Then
BindData()
End If
End Sub
Private Sub btnDelete_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
Dim i As Integer = 0
Dim cb As CheckBox
Dim dgi As DataGridItem
Dim id As Integer
dim con as new SQlConnection( connectionstring)
con.open()
dim cmd as new SQLCommand("delete from sometable where id = @id",con)
dim p as new SQLParameter("@id",sqldbtype.int)
cmd.parameters.add(p)
For Each dgi In DataGrid1.Items
cb = CType(dgi.findcontrol("chkdelete"), CheckBox)
If cb.Checked Then
id = CType( DataGrid1.DataKeys(i), Integer) ' get primary key
p.value = uid
try
cmd.ExecuteNonQuery()
catch ex as Exception
response.write( ex.message)
end try
End If
i += 1
Next
con.close()
binddata()
End Sub
Sub BindData()
Dim myConnection As New SqlConnection(ConnectionString)
Dim myCommand As New SqlDataAdapter("select * from sometable", myConnection)
Dim ds As New DataSet()
myCommand.Fill(ds)
DataGrid1.DataSource = ds
DataGrid1.DataBind()
End Sub
</script>
<html>
<body>
<form runat="server">
<asp:datagrid id="DataGrid1" runat="server" DataKeyField="id">
<Columns>
<asp:templateColumn>
<headertemplate>Delete</headertemplate>
<itemtemplate>
<asp:checkbox id=chkdelete runat="server"></asp:checkbox>
</itemtemplate>
</asp:templateColumn>
</Columns>
</asp:datagrid>
<p/>
<asp:button id="btndelete" runat="server" text="Delete" onclick="btndelete_click"/>
</form>
</body>
</html>