0

When a Button in the GridView is clicked I can't seem to get the row index or the row that is to be eliminated, I need the Id and the Complete route of the archive, both of them are on the bound fields of the GridView, here is the code I have:

Gridview Code:

<asp:GridView ID="gdvData"
              AllowSorting="False" 
              AllowPaging="True" 
              AutoGenerateColumns="False" 
              AutoGenerateDeleteButton="False" 
              runat="server" 
              EmptyDataText="No existen archivos cargados." 
              Width="100%">
    <AlternatingRowStyle CssClass="alternatingrowstyle" />
    <Columns>
        <asp:BoundField HeaderText="Id"
                   DataField="Id"
                   Visible="false" >
       <HeaderStyle CssClass="left" />
       <ItemStyle CssClass="left" />
       </asp:BoundField>
       <asp:BoundField HeaderText="RutaCompleta"
                   DataField="RutaCompleta"
                   Visible="false" >
       <HeaderStyle CssClass="left" />
       <ItemStyle CssClass="left" />
       </asp:BoundField>
        <asp:TemplateField HeaderText="Archivo">
            <ItemTemplate>          
                <asp:HyperLink runat="server"
                               CssClass="left"  
                               Target="_blank" 
                               NavigateUrl='<%#Eval("RutaCompleta")%>'  
                               Text='<%#Eval("Archivo")%>'> 
                </asp:HyperLink>             
            </ItemTemplate>
            <HeaderStyle CssClass="left" />
            <ItemStyle HorizontalAlign="left" />
        </asp:TemplateField>
        <asp:TemplateField HeaderImageUrl="~/Images/page_delete.ico"
                           HeaderText="Eliminar">
           <ItemTemplate>
           <asp:ImageButton ID="ImgDelete"
                            runat="server" 
                            CommandArgument="Delete"
                            ImageUrl="~/Images/page_delete.ico" 
                            OnClick="btnEliminar_Click"
                            OnClientClick="return confirm('¿Esta seguro de eliminar este archivo?');" 
                            ToolTip="Borrar Documento"/>                                                      
           </ItemTemplate>
           <HeaderStyle CssClass="center" />
           <ItemStyle CssClass="center"/>
        </asp:TemplateField> 
    </Columns>
    <HeaderStyle CssClass="headerstyle" />
    <PagerStyle CssClass="pagerstyle" />
    <PagerTemplate>
        <asp:Label ID="Label1" runat="server" Text="Mostrar filas:" />
        <asp:DropDownList   ID="ddlPageSize" 
                            runat="server" 
                            AutoPostBack="true" 
                            CssClass="CombosBox"
                            >
            <asp:ListItem Value="10" />
            <asp:ListItem Value="15" />
            <asp:ListItem Value="20" />
        </asp:DropDownList>
        <asp:Label ID="lblDesde" runat="server" Text="Página" />
        <asp:TextBox    ID="txtGoToPage" 
                        runat="server" 
                        AutoPostBack="true" 
                        CssClass="gotopage"
                        />
        <asp:Label ID="lblHasta" runat="server" Text="de " />
        <asp:Label ID="lblTotalNumberOfPages" runat="server" />
        <asp:Button ID="btnAnt" 
                    runat="server" 
                    CommandArgument="Prev" 
                    CommandName="Page" 
                    CssClass="previous" 
                    ToolTip="ant. página" />
        <asp:Button ID="btnProx" 
                    runat="server" 
                    CommandArgument="Next" 
                    CommandName="Page" 
                    CssClass="next" 
                    ToolTip="prox. página" />
    </PagerTemplate>
</asp:GridView>

Code Behind:

protected void btnEliminar_Click(object sender, EventArgs e)
{
    try
    {
        Int64 intId = 0;
        String strRutaCompleta = String.Empty;

        GridViewRow row = (GridViewRow)(sender as Control).Parent.Parent;
        Label lblId = (Label)row.FindControl("lblId");
        Label lblRutaCompleta = (Label)row.FindControl("lblRutaCompleta");

        intId = Convert.ToInt64(lblId.Text.ToString());
        strRutaCompleta = lblRutaCompleta.Text.ToString();

        /*Other part of the code*/
    }
    catch(Exception)
    {
        /*Other part of the code*/
    }
}

I have tried various methods found here on StackOverflow, hope you guys can help me. Thanks.

Chris
  • 2,045
  • 1
  • 18
  • 21

1 Answers1

0

Instead of using .Parent.Parent, I recommend using the CommandArgument property of the ImageButton and set the dataitem's Id.

Here is another post on StackOverflow that give a good bit of code: ASP.NET GridView RowIndex As CommandArgument

It appears to me that all you need is the Id of the data you want to delete. So instead of trying to use the row's index, just put the Id in the button's CommandArgument

Example:

<asp:ImageButton ID="ImgDelete"
                  runat="server" 
                  CommandArgument="Delete"
                  ImageUrl="~/Images/page_delete.ico" 
                  OnClick="btnEliminar_Click"
                  CommandArgument='<%#Eval("Id")%>'
                  OnClientClick="return confirm('¿Esta seguro de eliminar este archivo?');" 
                  ToolTip="Borrar Documento"/>

Code Behind:

protected void btnEliminar_Click(object sender, EventArgs e)
{
    try
    {
        Int64 intId = 0;
        ImageButton btn = (sender as ImageButton)
        if(btn != null)
        {
            Int64 tempId;
            if(Int64.TryParse(btn.CommandArgument, out tempId))
            {
                intId = intId;

                /*Other part of the code*/
            }
        }
    }
    catch(Exception)
    {
        /*Other part of the code*/
    }
}
Community
  • 1
  • 1
Chris
  • 2,045
  • 1
  • 18
  • 21
  • Well the data comes from a DataSet that is then bound to the gridview, how should I change the data? – Andres Scarpone Apr 28 '13 at 15:38
  • try: `.Container.Components.Item[rowIndex]` – Chris Apr 28 '13 at 15:51
  • Alternatively, you can grab the GridViewRow using the index as well: `gdvData.Rows[rowIndex]` – Chris Apr 28 '13 at 15:53
  • ok I have gotten the row using the next sentence: GridViewRow row = gdvData.Rows[index]; but how can i acces the column or cell?? – Andres Scarpone Apr 28 '13 at 17:02
  • @AndresScarpone, to be honest, I'm not exactly sure how your `DataSet` is structured. Normally I would have bound a `DataTable` or better yet, an `IEnumberable` of objects, to the `GridView`. You can try `gridViewRow.DataItem` ... but really you should be interacting with the `DataSet` directly. – Chris Apr 28 '13 at 17:21
  • well the dataset contains everithyng from a SQL statement and bring only the data that is bound in the Gridview, the id, The complete route and the archive. – Andres Scarpone Apr 28 '13 at 17:24
  • Then try: `DataRow dr = myDataSet.Tables[0].Rows[rowIndex];` ... beyond that you're going to need to set a breakpoint, examine the dataset in memory using *Watch Expressions* and determine how to access your data. – Chris Apr 28 '13 at 17:30
  • but the delete method doesn't have the dataset, the only moment the dataset is populated is when the page is loaded. – Andres Scarpone Apr 28 '13 at 17:34
  • Then store the `DataSet` in a variable in the page. The `Page_Load` will always occur before the button's `Click` event. – Chris Apr 28 '13 at 17:46
  • is there any other way to just get the data contained in the gridview??? I mean all the data should already be on it? – Andres Scarpone Apr 28 '13 at 17:51
  • So I tried to use this GridViewRow row = gdvData.Rows[index]; intId = Convert.ToInt64(row.Cells[0]); but at the moment of converting the row.cells[0] it gave me the following error: "Unable to cast object of type 'System.Web.UI.WebControls.DataControlFieldCell' to type 'System.IConvertible'." – Andres Scarpone Apr 28 '13 at 19:19
  • @AndresScarpone: I've updated my answer to store the `Id` in the `CommandArgument`. To be honest, there is a way to get "the data contained in the gridview" in the button's click event, but that question is worthy of a new question post. Good luck! – Chris Apr 28 '13 at 20:48
  • Yeah but with this method I can't get the route where the Archive is to delete it, but thanks for the method, ill try it later. – Andres Scarpone Apr 28 '13 at 22:05