• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1101
  • Last Modified:

ASP.net adding buttons to rows of an unbound GridView


I have an unbound GridView: gvCompanies, which I populate as follows:

SQLQuery = "EXEC AdmListCompaniesForNewsArticle " & Request.QueryString("neid")
      cmdQuery = New SqlCommand(SQLQuery, DBCon)
      rdrResults = cmdQuery.ExecuteReader

      dtTable = New DataTable()

      Do While rdrResults.Read
        drRow = dtTable.NewRow
        drRow("Name") = rdrResults!name

      gvCompanies.DataSource = dtTable


I would like to add a button to each row, which will delete that entry in the table.

The button must act within the code behind, rather than going to a new page, as there is likely to be other unsaved fields on the page.

Can I do this with this structure, and if so, how?


1 Solution
Rajar AhmedConsultantCommented:
Try like below,
<%@ Page Language="VB" AutoEventWireup="false" CodeFile="deleteRowGrid.aspx.vb" Inherits="Vb_deleteRowGrid" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <form id="form1" runat="server">
      <asp:GridView ID="gvData" runat="server" Width="50px" 
         AutoGenerateColumns="false"  DataKeyNames="ID">
     <asp:BoundField DataField="Id" HeaderText="ID" />
     <asp:BoundField DataField="Name" HeaderText="Name" />
     <asp:TemplateField  HeaderText="Delete" ItemStyle-Width="1px">
     <ItemTemplate >
     <asp:button id="btnText" runat="server" Text="Delete" OnClick="btnText_Click"></asp:button>
Imports System.Data
Imports System.Data.SqlClient

Partial Class Vb_deleteRowGrid
    Inherits System.Web.UI.Page

    Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
        Dim ds As DataSet = getDataSet()
        If Not IsPostBack Then
            gvData.DataSource = ds
        End If
    End Sub
    Public Shared Function getDataSet() As DataSet
        Dim ds As New DataSet
        Dim dt As DataTable
        Dim dr As DataRow
        Dim idCoulumn As DataColumn
        Dim nameCoulumn As DataColumn
        Dim i As Integer

        dt = New DataTable()
        idCoulumn = New DataColumn("ID", Type.GetType("System.String"))
        nameCoulumn = New DataColumn("Name", Type.GetType("System.String"))


        dr = dt.NewRow()
        dr("ID") = "1"
        dr("Name") = "Bill"

        dr = dt.NewRow()
        dr("ID") = 2
        dr("Name") = "Gates"

        Return ds
    End Function

    Protected Sub btnText_Click(sender As Object, e As EventArgs)
        Dim lnkbtn As Button = TryCast(sender, Button)
        'getting particular row linkbutton
        Dim gvrow As GridViewRow = TryCast(lnkbtn.NamingContainer, GridViewRow)
        'getting userid of particular row
        Dim userid As Integer = Convert.ToInt32(gvData.DataKeys(gvrow.RowIndex).Value.ToString())
        Dim username As String = gvrow.Cells(1).Text
        'Dim cmd As New SqlCommand("delete from UserDetails where UserId=" + userid, con)
        'Dim result As Integer = cmd.ExecuteNonQuery()
        ' con.Close()
        Dim result As Integer = 1
        If result = 1 Then
            ' BindUserDetails()
            ScriptManager.RegisterStartupScript(Me, Me.[GetType](), "alertmessage", "javascript:alert('" + username + " details deleted successfully')", True)
        End If

    End Sub
End Class

Open in new window

Jerry MillerCommented:
I would follow meeran03's code, just make sure that you use the unique ID for that record in the button click event.

Another way to do it is by using the CommandName='Delete' and in the rowCommand event for the gridview, do a If e.CommandName = 'Delete' and perform your delete query. I believe that the RowCommand option exposes the RowIndex so you can be sure to grab the correct record. You use the RowIndex to capture the ID of the record and send that to the database.
rpmAuthor Commented:
Great answer, thanks!

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Tackle projects and never again get stuck behind a technical roadblock.
Join Now