RG-3
RG-3

Reputation: 6188

Accessing items in GridView

I have a GridView and I am updating it through LINQ through C#. I want to access the elements in my GridView and store them in the variable. Then I will pass these variables into my LINQ query.

How should I access the items in my GridView? Here is my code:

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();
}

Markup:

<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>

Upvotes: 0

Views: 1092

Answers (2)

Josh
Josh

Reputation: 44906

The GridViewUpdateEventArgs has properties on it that allow you to get at the Keys, OldValues, and NewValues collections for a particular row.

You could access it like so:

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...
}

But this sucks pretty hard! ASP.Net can do the work for you, using one of the DataSource classes available. For your purposes you should look into the LinqDataSource

It is worth noting that while the DataSource classes can be useful and nice, they have quite a bit of magic going on, and you can pretty much throw out the possibility of using any testable patterns with them. (see WebFormsMVP)

If that isn't a concern, then go for it. But achieving clean separation of concerns is better in the long run. In that case you would need to implement a facade wrapper around your business logic and use the ObjectDataSource.

Either way you are better off than manually rooting around in key/value pair collections looking for values and then converting them back to their proper types.

Upvotes: 1

Bala R
Bala R

Reputation: 108957

Something like Produce_ID sounds like a key field and if it is, you can do

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

or else

there is e.NewValues[] and e.OldValues[] that you could use.

Upvotes: 2

Related Questions