将实体绑定到gridview

时间:2012-03-23 19:08:13

标签: c# asp.net gridview entity-framework-4 ado.net

enter image description here

idc = courseID

之间的关系

网格视图的HTML

   <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="id"
    DataSourceID="EntityDataSource1">
        <Columns>
            <asp:BoundField DataField="course" HeaderText="course" SortExpression="courseID" />
           <asp:BoundField DataField="id" HeaderText="id" ReadOnly="True" SortExpression="id" />
        </Columns>
    </asp:GridView>
<asp:EntityDataSource ID="EntityDataSource1" runat="server" ConnectionString="name=dbEn"
    DefaultContainerName="dbEn" EntitySetName="userCourses">
</asp:EntityDataSource>

现在网格视图只显示CourseID,但我想要显示名称。

如何在网格视图中显示课程名称而不是courseID?

1 个答案:

答案 0 :(得分:0)

嘿,你必须绑定“Course”EntitySetName而不是“userCourses”和

 <Columns> 
            <asp:BoundField DataField="name" HeaderText="course" SortExpression="name" /> 
            <asp:BoundField DataField="idc" HeaderText="ID" ReadOnly="True" SortExpression="id" /> 

        </Columns> 

你必须编写commandText

<asp:EntityDataSource
   ID="EntityDataSource"
   ConnectionString="name=dbEn"
   DefaultContainerName="dbEn"
   CommandText="
      SELECT c.Name,uc.ID
      FROM Course c
      Inner JOIN userCours uc ON c.IDc=uc.CourseID"
   RunAt="server">
</asp:EntityDataSource>

更多参考:link

MSDN