如何从ASP WebForm GridView获取数据ID

时间:2019-01-15 18:50:23

标签: c# asp.net webforms

我有一个带有gridview的Web表单。第一列有一个按钮“更新”和“删除”。我想要的是,当我单击“删除”按钮代码时,获得了我的第三列中的ID。

使用下面的代码我只会得到“ 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();
}

1 个答案:

答案 0 :(得分:0)

使用CommandArgument定位按索引的行并不是一种好习惯,因为可以通过例如排序来更改行顺序。


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>