5

I want to access a value in a radGrid control. Given the image below, I want to access the value of "Status". But I can't seem to get it.

I get an error message

"Unable to cast object of type 'TripLeg' to type 'Telerik.Web.UI.GridDataItem'."

Any ideas how to access that column?

GridItem

Csharp
  • 2,916
  • 16
  • 50
  • 77
  • I notice that you check to make sure `hLink` is not null. However, it'll throw exception (if `hLink` is null) before reaching `if (hLink != null)`. Please see my answer. – Win May 12 '13 at 02:56

2 Answers2

4

You are almost there. You just need to cast DataItem to appropriate object. Let assume your data source is IEnumerable<TripLeg>.

Here is the example -

if (e.Item is GridDataItem)
{
   var item = e.Item as GridDataItem;
   var tripLeg = e.Item.DataItem as TripLeg; // Cast to appropriate object
   var status = tripLeg.Status; 

   // var hLink = (HyperLink) item.FindControl("HyperLink1");
   // Above code will throw exception if the control is not found.

   var hLink = item.FindControl("XXXXX") as HyperLink;
   if(hLink != null)
   {
      hLink.Attributes.Add("XXXXX", "XXXXX");
   }
}
Win
  • 61,100
  • 13
  • 102
  • 181
  • I think for this to work the 'Tripleg' object has to be of type GridDataItem which is a type that exists within the RadGrid only, even if the conversion was successful why would you want to waste resources converting if you can access the value directly from the RadGrid control – Marcianin May 10 '13 at 23:48
  • @Marcianin - `DataItem` must be of type `TripLeg` (not the other way around). In order for your answer to work, you must have `GridBoundColumn` with `UniqueName="ColumnUniqueName"` inside `RadGrid`. In OP, Csharp wants to assign `Status` property of `Tripleg` to `HyperLink` control located inside `GridTemplateColumn`. – Win May 11 '13 at 18:00
  • Look at the picture, he already has the status value in the gItem.DataItem all he needs it to access that data and my solution will access the data and assign it to the string. My point is that he does not need to convert to anything, he already has the value he needs all he has to do is access it. GridDataItem is like a DataRow in GridView, Telerik controls are regular ASP controls on steroids! so can access the data on a DataRow by just querying the column that has it – Marcianin May 11 '13 at 19:08
3

I like Telerik Components a lot (altough more and more I like Kendo UI) anyway seems to me that if you want to get the value on the status you could use this

string itemValue = dataItem["ColumnUniqueName"].Text;
//no need to convert :)

Take a look at the Documentation for the RadGrids... http://www.telerik.com/help/aspnet-ajax/grid-accessing-cells-and-rows.html

Marcianin
  • 461
  • 3
  • 8