0

I have a webform with a gridview. The first column has a button "Update" and "Delete". What I want is when I click the delete button code gets the id which was in my 3rd column.

Using the below code I only get "1"

if (e.CommandName == "Delete")
{
    int id = Convert.ToInt32(e.CommandArgument);
    GridViewRow row = GridView1.Rows[id];

    Add_update delete = new Add_update();
    delete.deleteVehicle(Convert.ToInt32(id));
    reload();
}
Nathan Champion
  • 1,291
  • 1
  • 14
  • 23
  • Well what does your GridView look like? Are you setting the ID into the CommandArgument? See a similar question here: https://stackoverflow.com/questions/24773645/in-gridview-how-to-use-rowcommand-event-for-a-button – Nathan Champion Jan 15 '19 at 19:05
  • Where do get `1`? Beccause there is nothing wrong with the code (apart from converting an int to an int again). As long as you give the correct value to the `CommandArgument` of the button it should work. – VDWWD Jan 15 '19 at 21:38

1 Answers1

0

It is not good practice use CommandArgument to target on the Row by index, because rows order can be changed by sorting for instance.


public partial class _Default : Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                var dataObjects = new List<DataObject>();

                for (int i = 0; i < 100; i++)
                {
                    dataObjects.Add(new DataObject() { Index = i });
                }

                gridView1.DataSource = dataObjects;
                gridView1.DataBind();
            }
        }

        protected void gridView1_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName == "Delete")
            {
                var dataObjectIndex = int.Parse((string) e.CommandArgument);
                e.Handled = true;
            }
        }
    }

    public class DataObject
    {
        public int Index { get; set; }
    }


    <asp:GridView ID="gridView1" runat="server" OnRowCommand="gridView1_RowCommand" AutoGenerateColumns="false">
        <Columns>
            <asp:BoundField DataField="Index" HeaderText="Index" />
            <asp:TemplateField>
                <ItemTemplate>
                    <asp:Button ID="btnDelete" runat="server" CommandName="Delete" CommandArgument='<%# Bind("Index") %>' />
                </ItemTemplate>
            </asp:TemplateField>
        </Columns>
    </asp:GridView>