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

ASP.net adding buttons to rows of an unbound GridView

Hi,

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()
      dtTable.Columns.Add("Name")

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

      gvCompanies.DataSource = dtTable
      gvCompanies.DataBind()

      rdrResults.Close()
      cmdQuery.Dispose()


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?

Thanks,

Richard
0
rpm
Asked:
rpm
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">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
      <asp:GridView ID="gvData" runat="server" Width="50px" 
         AutoGenerateColumns="false"  DataKeyNames="ID">
     <Columns>
     <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>
     </ItemTemplate>
     
     </asp:TemplateField>
  
            </Columns>
     </asp:GridView>
    </div>
    </form>
</body>
</html>
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
            gvData.DataBind()
        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"))

        dt.Columns.Add(idCoulumn)
        dt.Columns.Add(nameCoulumn)

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

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

        ds.Tables.Add(dt)
        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
        'con.Open()
        '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

0
 
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.
0
 
rpmAuthor Commented:
Great answer, thanks!
0

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