如何使用密钥将DataTextField绑定到字典值

时间:2013-09-04 03:06:00

标签: c# mysql dictionary radgrid

我正在使用Telerik的RadGrid,我希望能够将动态创建的列的DataTextField绑定到我用作数据源的对象内的字典中的值。

我的课程结构如下:

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

我正在动态创建列,我想以这种方式设置列的DataTextField:

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";
}

如果数据源已设置为MyClass对象列表,并且填充了该字典,则OID将用作字典键。

这基本上是带有MySQL后端的数据透视表的radgrid视图。这是可能的,还是钻入字典项对于DataTextField来说太多了?我在这里看到的大多数问题与下拉有关,这不是我正在尝试的。

1 个答案:

答案 0 :(得分:0)

我有完全相同的问题。

我发现将 GridHyperLinkColumn DataTextField 绑定到字典值的唯一方法是在网格的 ItemDataBound 事件中。< / p>

以下示例基于您的示例结构:

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

我希望这对你有用。

相关问题