将Linq.EntityRef绑定到Gridview

时间:2013-11-15 18:35:43

标签: c# asp.net linq

我有一个名为ds_User的表创建的linq对象。 ds_User在ds_User.GroupID = ds_NetworkGroup.GroupID上具有名为ds_NetworkGroup的表的外键。当我填充ds_User的通用列表时,我通过System.Data.Linq.EntityRef获得与每个条目关联的ds_NetworkGroup。我现在通过显式创建每一列将我的ds_User绑定到gridview。但是,我想显示ds_NetworkGroup.Name而不是ds_User.GroupID。我尝试了DataField =“ds_NetworkGroup.Name”,但错误。有没有办法做到这一点?

        <asp:GridView runat="server" ID="UsersGV" CellPadding="4" ForeColor="#333333" 
        GridLines="None" 
        OnRowEditing="UsersGV_RowEditing"
        OnRowCancelingEdit="UsersGV_CancelEdit"
        OnRowUpdating="UsersGV_Updating"
        OnRowDeleting="UsersGV_Deleting" AutoGenerateColumns="False"
        >
        <AlternatingRowStyle BackColor="White" />
        <Columns>
            <asp:CommandField ShowEditButton="True" ShowDeleteButton="True" />
            <asp:BoundField DataField="FirstName" HeaderText="FirstName" />
            <asp:BoundField DataField="LastName" HeaderText="LastName" />
            <asp:BoundField DataField="GroupId" HeaderText="GroupId" />
            <asp:BoundField DataField="UserID" HeaderText="UserID" />
            <asp:DynamicField DataField="ds_NetworkGroup.Name" HeaderText="GroupName" />
        </Columns>
        <EditRowStyle BackColor="#2461BF" />
        <FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
        <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
        <PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
        <RowStyle BackColor="#EFF3FB" />
        <SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
        <SortedAscendingCellStyle BackColor="#F5F7FB" />
        <SortedAscendingHeaderStyle BackColor="#6D95E1" />
        <SortedDescendingCellStyle BackColor="#E9EBEF" />
        <SortedDescendingHeaderStyle BackColor="#4870BE" />
    </asp:GridView>


    public List<ds_User> GetAllUsers()
    {
        List<ds_User> allUsers = DC1.ds_Users.ToList();
        return allUsers;
    }


    private void BindGrid()
    {
        UserClass myUsers = new UserClass();

        List<ds_User> users = new List<ds_User>();
        users = myUsers.GetAllUsers();

        if (users.Count > 0)
        {
            UsersGV.DataSource = users;
            UsersGV.DataBind();
        }
    }

1 个答案:

答案 0 :(得分:0)

这就是我最终做的事情:

    <asp:TemplateField HeaderText="GroupName" SortExpression="GroupName">
        <ItemTemplate><asp:Label ID="lblGroupName" runat="server" Text='<%#Eval("ds_NetworkGroups.Name")%>'></asp:Label></ItemTemplate>
    </asp:TemplateField>

非常简单......只是尝试了一些试验和错误。