views:

986

answers:

3

I have a GridView control bound to an ObjectDataSource which returns a list of objects that look like this:

public class X {
    public string DisplayName {
        get;
    }
    public string Guid {
        get;
    }
}

I don't want to show the Guid property in the GridView, but I need to retrieve it when an object is selected.
I could not find a "DataValueField" property, like for the ListBox control.
As a workaround, I tried to set Visible=false for the column bound to the Guid property and get the cell text from the Row object in the SelectedIndexChanged method:

protected void GridView1_SelectedIndexChanged(object sender,EventArgs e){
    GridViewRow row = GridView1.SelectedRow;
    string id = row.Cells[2].Text; // empty
}

But this does not work - apparently if the column is not visible its Text property is left empty.

How can I get the Guid of the selected object while showing only the DisplayName?

A: 

Can't you use row.DataItem to get the object itself?

Fiona Holder
In my case row.DataItem is null... how is is supposed to work?
Paolo Tedesco
The DataItem is not persisted on postback, I guess you would have to get it on a data bind event or something like that. The other answer looks best in your scenario though.
Fiona Holder
+4  A: 

Not sure about how this works with ObjectDataSource, but with SqlDataSource we set keys on the rows of the GridView.

GridView1.DataKeyNames = new String[] {"Guid"};

Then, you can get the key by doing this:

string guid = GridView1.DataKeys[GridView1.SelectedRow.RowIndex];
Matthew Jones
Thank you, that's what I was looking for!
Paolo Tedesco
+1  A: 

Add "Guid" into the DataKeyNames property of the GridView. That will allow it to be available even though the column is hidden.

Ken Pespisa
Actually you can even remove the column...
Paolo Tedesco