haydnD
haydnD

Reputation: 2293

delete gridview row Programmatically

I keep returning an error when trying to delete a row in my gridview (Input string was not in a correct format)

Not sure what I'm doing wrong. Any help?

<asp:GridView ID="favoritesGrid" runat="server" OnRowDeleting ="favoritesGrid_RowDeleting">
    <columns>
        <asp:CommandField HeaderText="Delete" ShowDeleteButton="True"/>
        <asp:BoundField HeaderText="FavoritesId" DataField="FavoritesId"/>
        <asp:TemplateField HeaderText="Site Name">
             <ItemTemplate>
                 <asp:HyperLink ID="myHyperlink"
                                Text='<%# Eval("SiteName") %>'
                                NavigateUrl='<%# Eval("Url") %>'
                                runat="server">

                 </asp:HyperLink>
             </ItemTemplate>
        </asp:TemplateField>

    </columns>
</asp:GridView>



   protected void favoritesGrid_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        var delId = Convert.ToInt32(favoritesGrid.Rows[e.RowIndex].Cells[0].Text);
        //var id = favoritesGrid.Rows[e.RowIndex].Cells[0].Text;
        var delFavorites = new FavoritesDb();
        var delFavs = delFavorites.DeleteFavorite(delId);
        DataBind();
    }

Upvotes: 0

Views: 4739

Answers (1)

Amiram Korach
Amiram Korach

Reputation: 13286

The cell at position 0 has the word "delete" in it and it cannot be converted to int. You need to use:

var delId = Convert.ToInt32(favoritesGrid.Rows[e.RowIndex].Cells[1].Text);

However, this is not a good approach since you might change the cells order or add a new one. You'd better use the DataKeyNames attribute.

aspx:

<asp:GridView DataKeyNames="FavoritesId" ...>

C#:

Convert.ToInt32(favoritesGrid.DataKeys[e.RowIndex].Value);

Upvotes: 1

Related Questions