Rowcommand VB.Net

Asked

Viewed 455 times

1

I have the following problem deleting a line from asp:gridview.

When I leave the code(key) visible="false" in the gridview, the value returned in my variable key comes Empty. But when I let visible="true" the function takes the correct value, someone knows a solution to take the value even with the 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
  • 1

    Managed to solve the problem?

  • 1

    It worked perfectly dude, vlw!!!

  • I am happy to have helped :). If possible mark the answer as accepted.

1 answer

1

One of manners to do this is to 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 the 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:

Browser other questions tagged

You are not signed in. Login or sign up in order to post.