I use problems binding RadGrid to Entity Framework-objects.
I have two tables:
User:
UserID
Name
Age
GroupID
Group:
GroupID
Name
In entity framework, i get two Entitytypes. First User with properties UserID, Name, Age and Navigation property Group. Entity set name is set to Users. Second EntityType is Group with GroupID and Name as properties, and a navigation property named Users pointing to a collection of User-entities.
To fetch all users and include the group i use the following code:
| private List<User> GetUsers() |
| { |
| var users = from u in entities.Users |
| .include("Group") |
| select u; |
| return users.ToList(); |
| } |
Binding the grid to the list of User-objects is no problem.
| Grid.Datasource = GetUsers(); |
| Grid.Databind(); |
I add the following columns to the grid.
| <telerik:GridBoundColumn DataField="Name" UniqueName="Name" HeaderText="Name" /> |
| <telerik:GridBoundColumn DataField="Age" UniqueName="Age" HeaderText="Age" /> |
| <telerik:GridBoundColumn DataField="Group.Name" UniqueName="Group" HeaderText="Group Name" /> |
All data is displayed, no problem yet.
I want the 3rd column to be a GridDropDownColumn instead. I tried to use a GridDropDownColumn, but it didn't work, all rows were blank:
| <telerik:GridDropDownColumn DataField="Group.Name" UniqueName="Group" HeaderText="Group" /> |
I read in another thread that GridDropDownColumn is mainly for DataTables, so i tries to use GridTemplateColumn instead, and it almost works.
| <telerik:GridTemplateColumn DataField="Group.Name" UniqueName="Group" HeaderText="Group"> |
| <ItemTemplate> |
| <asp:Label ID="Label1" runat="server" Text='<%#Bind("Group.Name") %>'></asp:Label> |
| </ItemTemplate> |
| <EditItemTemplate> |
| <telerik:RadComboBox ID="EditGroupRadComboBox" runat="server" /> |
| </EditItemTemplate> |
| </telerik:GridTemplateColumn> |
The RadComboBox is bound to data in ItemDataBound:
| if (e.Item is GridEditableItem && (e.Item as GridEditableItem).IsInEditMode) |
| { |
| GridEditableItem editedItem = e.Item as GridEditableItem; |
| RadComboBox combo = (RadComboBox)editedItem.FindControl("EditGroupRadComboBox"); |
| combo.DataSource = GetGroups(); //returns List<Group> |
| combo.DataTextField = "Name"; |
| combo.DataValueField = "GroupID"; |
| combo.DataBind(); |
| combo.SelectedValue = ((User)editedItem.DataItem).Group.GroupID.ToString(); |
| } |
It works as expected, the groups are displayed in the RadComboBox, and the correct option is selected.
Now to the problem, how do I perform the update? I tried he following in ItemCommand-event, but the user-object contains the old values
| if (e.CommandName == "Update") |
| { |
| User user = e.Item.DataItem as User; |
| } |
I looked at the following thread, with a similar problem: http://www.telerik.com/community/forums/aspnet-ajax/grid/radcombobox-in-gridtemplatecolumn.aspx
I tried to set SelectedValue='<%#Bind("Group.GroupID") %>', but i get an exception, saying Group.GroupID is invalid.
Kind Regards, Johan