访问GridView中的项

本文关键字:GridView 访问 | 更新日期: 2023-09-27 17:49:21

我有一个GridView,我正在通过LINQ通过c#更新它。我想访问GridView中的元素并将它们存储在变量中。然后我将这些变量传递到我的LINQ查询中。

我应该如何访问项目在我的GridView?下面是我的代码:

protected void gvShowComm_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
    string productID = gvShowComm.DataKeys[e.RowIndex]["Product_ID"].ToString(); //Working!
    string planName = gvShowComm.DataKeys[e.RowIndex]["PlanName"].ToString(); //Working!
    string hiComm = gvShowComm.DataKeys[e.RowIndex]["HiCommissionOld"].ToString(); //Working!
    string lowComm = gvShowComm.DataKeys[e.RowIndex]["LowCommissionOld"].ToString(); //Working!
    gvShowComm.DataBind();
}

标记:

<asp:GridView runat="server" Height="233px" Width="602px" ID ="gvShowComm" 
    CellPadding="4" ForeColor="#333333" GridLines="None" OnRowEditing = "gvShowComm_RowEditing" 
    OnRowUpdating = "gvShowComm_RowUpdating" 
    OnRowCancelingEdit = "gvShowComm_RowCancelingEdit" DataKeyNames = "Product_ID, PlanName, HiCommissionOld, LowCommissionOld">       
    <Columns>
        <asp:CommandField ShowCancelButton="True" ShowEditButton="True" />
    </Columns>
</asp:GridView>

访问GridView中的项

像Produce_ID这样的东西听起来像是关键字段如果是,你可以使用

var keyValue =  gvShowComm.DataKeys[e.RowIndex].Value;
if(keyValue!=null)
int Product_ID = Convert.ToInt32(keyValue);

或者

你可以使用e.NewValues[]e.OldValues[]

GridViewUpdateEventArgs具有允许您获取特定行的Keys, OldValues和NewValues集合的属性。

可以像这样访问它:

protected void gvShowComm_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
    //Product_ID is a column that I am displaying in my GV!
    int Product_ID = Int32.Parse(e.Keys["Product_ID"]);
    Entity_Product_Point ev = new Entity_Product_Point();
    ev.MyDateTime = DateTime.Parse(e.NewValues["MyProp"]);
    // And so on...
}

但是这很糟糕!ASP。Net可以使用一个可用的DataSource类为您完成这项工作。为了达到目的,您应该查看LinqDataSource

值得注意的是,虽然DataSource类可能很有用而且很漂亮,但它们有相当多的魔力在起作用,并且您几乎可以放弃对它们使用任何可测试模式的可能性。(见WebFormsMVP)

如果这不是一个问题,那就去做吧。但从长远来看,实现关注点的彻底分离会更好。在这种情况下,您需要在业务逻辑周围实现一个外观包装器,并使用ObjectDataSource。

无论哪种方式,您都比手动在键/值对集合中查找值然后将它们转换回正确的类型要好。