Question

I'm working with the RadGrid from Telerik and I'd like to be able to bind a dynamically created column's DataTextField to a value inside a dictionary inside object I'm using as a data source.

I've got a class structured so:

public class MyClass
{
    public AnObject ThisObject = null;
    public Dictionary<int, ClassWithStuff> AnotherObject = new Dictionary<int, ClassWithStuff>();
}

I'm dynamically creating columns, and I'd like to set the column's DataTextField in something like this fashion:

foreach (var item in ListOfPeople.OrderBy(r => r.FormattedName))
{
    var col = new GridHyperLinkColumn();
    rgGrid.MasterTableView.Columns.Add(col);
    col.HeaderText = item.FormattedName;
    col.NavigateUrl = string.Format("~/Person.aspx?id={0}", item.OID);
    col.UniqueName = item.OID.ToString();
    col.DataTextField = "AnotherObject[" + item.OID + "].Person.FormattedName";
}

Where the datasource has been set to a List of objects of MyClass and when that dictionary is populated, the OID is used as the dictionary key.

This is basically a radgrid view of a pivot table with a MySQL backend. Is this possible, or would drilling into a dictionary item be too much for a DataTextField? Most of the questions I see here are related to drop-downs, which isn't what I'm attempting.

Was it helpful?

Solution

I had exactly the same issue.

The only way that I found for binding a DataTextField of GridHyperLinkColumn to a dictionary value is on the ItemDataBound event of the grid.

The following example is based on your sample structure:

...
// set temporary the ID as a text
col.Text = item.OID.ToString();
YourGrid.ItemDataBound += OnYourGridItemBound;
...
private static void OnYourGridItemBound(object sender, Telerik.Web.UI.GridItemEventArgs e)
{
    GridDataItem dataBoundItem = e.Item as GridDataItem;
    if (dataBoundItem != null)
    {
        foreach (TableCell cell in dataBoundItem.Cells)
        {
            if (cell.Controls.Count > 0)
            {
                var link = cell.Controls[0] as HyperLink;
                if (link != null)
                {
                    var dataItem = dataBoundItem.DataItem as MyClass;
                    var id = link.Text;
                    link.Text =                                     
                       dataItem.AnotherObject[id].Person.FormattedName;
                }
            }
        }
    }
}

I hope this will work for you.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top