RowCommand VB.Net

1

I'm having the following problem deleting a line from asp:gridview .

When I leave the code (key) visible="false" in gridview , the value returned in my variable Delete key comes empty . But when I leave visible="true" the function takes the correct value, does anyone know of a solution to get the value even with visible="false" of my key?

Protected Sub gvLivros_RowCommand(sender As Object, e As GridViewCommandEventArgs) Handles gvLivros.RowCommand
    Dim objLivros As New ClasseLivros

    If e.CommandName = "Excluir" Then
        Dim index As Integer = Integer.Parse(DirectCast(e.CommandArgument, String))
        Dim chaveDelete = gvLivros.Rows(index).Cells(0).Text

        objLivros.ExcluirLivro(Convert.ToInt32(chaveDelete))
    End If
End Sub
    
asked by anonymous 25.04.2015 / 13:54

1 answer

1

One of ways to do this is use the property DataKeyNames of GridView . To use it, simply specify the name of the column (s) in DataKeyNames .

<asp:GridView ID="gvLivros" runat="server" AutoGenerateColumns="false" DataKeyNames="Chave, Secao" OnRowCommand="gvLivros_RowCommand">
<Columns>
    <asp:BoundField DataField="Livro" HeaderText="Livro" ItemStyle-Width="150" />
    <asp:BoundField DataField="Preco" HeaderText="Preço" ItemStyle-Width="100" />
    <asp:ButtonField CommandName="Comprar" Text="Comprar" ButtonType="Button" />
</Columns>
</asp:GridView>

Populating GridView :

Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
    If Not Me.IsPostBack Then
        Dim dt As New DataTable()
        dt.Columns.AddRange(New DataColumn(3) {New DataColumn("Chave"), New DataColumn("Secao"), New DataColumn("Livro"), New DataColumn("Preco")})
        dt.Rows.Add(1, "A", "Foo", "5")
        dt.Rows.Add(2, "B", "Bar", "10")
        dt.Rows.Add(3, "A", "Baz", "15")
        dt.Rows.Add(4, "B", "Poo", "20")
        GridView1.DataSource = dt
        GridView1.DataBind()
    End If
End Sub

Event RowCommand :

Protected Sub gvLivros_RowCommand(sender As Object, e As GridViewCommandEventArgs)
    Dim index As Integer = Convert.ToInt32(e.CommandArgument)

    ' Obter o valor das colunas a partir de DataKeys usando como índice a variável index.
    Dim chave As Integer = Convert.ToInt32(gvLivros.DataKeys(index).Values(0))
    Dim secao As String = gvLivros.DataKeys(index).Values(1).ToString()
End Sub

Reference:

25.04.2015 / 16:52