Error trying to select field in my table gridview webform c #

0

The code for my gridview is this:

 <asp:GridView ID="ListaArticulos" CssClass="table table-bordered table-hover" autogeneratecolumns="false" runat="server" OnRowCommand="ListaArticulos_RowCommand">
    <Columns>
        <asp:ButtonField AccessibleHeaderText="Eliminar" Text="Eliminar" CommandName="CellEliminar"/>
        <asp:ButtonField AccessibleHeaderText="Editar" Text="Editar" CommandName="CellEditar"/>
        <asp:BoundField DataField="IDArticulo" HeaderText="Clave" SortExpression="Clave" />
        <asp:BoundField DataField="NombreArticulo" HeaderText="Articulo" SortExpression="Articulo" />
        <asp:BoundField DataField="Abreviado" HeaderText="Abreviado" SortExpression="Abreviado"/>
        <asp:BoundField DataField="Precio" HeaderText="Precio" SortExpression="Precio" />
        <asp:BoundField DataField="CantidadArticulo" HeaderText="Cantidad" SortExpression="Cantidad" />
    </Columns>
</asp:GridView>

and my method is this:

 protected void ListaArticulos_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        string idPro;

        /*if (e.CommandName == "CellEliminar")
        {

        }*/
        if(e.CommandName == "CellEditar")
        {
            idPro = ListaArticulos.SelectedRow.Cells[2].Text; //<-error aquí
            txtBuscar.Text = idPro;
            //Redireccionar(idPro);
        }
    }

When I try to access the field I get this error, it says that I do not refer to an object, but which object?

  

An exception of type 'System.NullReferenceException' occurred in ShoppingWebForm.dll but it was not handled in user code

     

Additional information: Object reference not established as   instance of an object.

As a solution, he asks me to refer to new, does someone explain to me what is happening or what is wrong?

    
asked by Alex Castro M 24.02.2017 в 20:43
source

1 answer

0

Alex,

I think it's not the correct way to access the gridview fields. I attached a block of code that allows you to obtain the values from the grid.

void ContactsGridView_RowCommand(Object sender, GridViewCommandEventArgs e) if(e.CommandName=="Add")
{
  int index = Convert.ToInt32(e.CommandArgument);
  GridViewRow row = ContactsGridView.Rows[index];

  ListItem item = new ListItem();
  item.Text = Server.HtmlDecode(row.Cells[2].Text) + " " +
    Server.HtmlDecode(row.Cells[3].Text);

  if (!ContactsListBox.Items.Contains(item))
  {
    ContactsListBox.Items.Add(item);
  }
}
    
answered by 26.02.2017 в 20:42