如何从事件中获取匿名类型数据项gridview_RowDeleting

本文关键字:数据项 类型 gridview RowDeleting 事件 获取 | 更新日期: 2023-09-27 18:33:39

我想从RowDelete事件中的GridView获取Id,我尝试过这样:

        protected void gvHouse_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            Guid hholder = (Guid)(e.Values[0]);
            using (var dataContext = new realtydbEntities())
            {
                var house = (from h in dataContext.Households.Include("aspnet_Users.aspnet_Membership")
                             where h.HouseholdID == hholder
                             select h).First();
                dataContext.DeleteObject(house);
                dataContext.SaveChanges();
            }
        }

但它不起作用。

匿名类型是这样的,我使用 List<<strong>this anonymousType> 绑定到 GridView 的数据源:

                         new
                         {
                             Id = u.HouseholdID,
                             BuNo = u.Building.BuildingName,
                             UnNo = u.UnitNo,
                             DepNo = u.DepartmentNo,
                             Name = u.aspnet_Users.UserName,
                             Corp = u.Corporation,
                             IdNumber = u.IdNumber,
                             Telephone = u.Telephone,
                             OtherHouseMembers = u.OtherHouseMembers,
                             OtherInfo = u.OtherInfo,
                             CrDate = u.aspnet_Users.aspnet_Membership.CreateDate
                         });

我想获取匿名对象或仅获取 ID 属性的值。

如何从事件中获取匿名类型数据项gridview_RowDeleting

如果您使用的是 .net 4,则可以像这样利用dynamic类型:

// Get the reference to the bound item
dynamic item = gvHouse.Rows[e.RowIndex].DataItem; 
// Access item property
var itemId = item.Id;

请记住,您的类型的任何属性都无法通过智能感知获得,您只需要避免拼写错误即可。

这会

让你得到ID

 var HouseHoldid = Guid.Parse(gvHouse.Rows[e.RowIndex].Cells[0].Text);

如果 ID 的类型为 int,则:

 var HouseHoldid = Convert.ToInt32(gvHouse.Rows[e.RowIndex].Cells[0].Text);

删除后,您还必须刷新数据源。从绑定列表中删除该项并刷新网格视图的数据源

这种方式可以获取数据源

protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
    DataTable sourceData = (DataTable)GridView1.DataSource;
    sourceData.Rows[e.RowIndex].Delete();
}