Solved adding buttons to rows of an unbound GridView

Posted on 2012-09-20
Last Modified: 2012-09-21

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?


Question by:rpm
    LVL 18

    Accepted Solution

    Try like below,
    <%@ Page Language="VB" AutoEventWireup="false" CodeFile="deleteRowGrid.aspx.vb" Inherits="Vb_deleteRowGrid" %>
    <!DOCTYPE html>
    <html xmlns="">
    <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

    LVL 18

    Expert Comment

    by:Jerry Miller
    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.
    LVL 1

    Author Closing Comment

    Great answer, thanks!

    Featured Post

    Highfive + Dolby Voice = No More Audio Complaints!

    Poor audio quality is one of the top reasons people don’t use video conferencing. Get the crispest, clearest audio powered by Dolby Voice in every meeting. Highfive and Dolby Voice deliver the best video conferencing and audio experience for every meeting and every room.

    Join & Write a Comment

    Suggested Solutions

    In .NET 2.0, Microsoft introduced the Web Site.  This was the default way to create a web Project in Visual Studio 2005.  In Visual Studio 2008, the Web Application has been restored as the default web Project in Visual Studio/.NET 3.x The Web Si…
    The ECB site provides FX rates for major currencies since its inception in 1999 in the form of an XML feed. The files have the following format (reducted for brevity) (CODE) There are three files available HERE (…
    This video discusses moving either the default database or any database to a new volume.
    This video gives you a great overview about bandwidth monitoring with SNMP and WMI with our network monitoring solution PRTG Network Monitor ( If you're looking for how to monitor bandwidth using netflow or packet s…

    755 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    21 Experts available now in Live!

    Get 1:1 Help Now