在Gridview中显示两个具有相同名称的列

时间:2013-09-24 18:46:48

标签: asp.net sql-server gridview

我有一个使用JOIN的gridview。这两个来自不同表的列具有相同的名称:

<asp:GridView ID="viewThemeTypeAssociationsGridView" runat="server" AutoGenerateColumns="False"
     BackColor="#DEBA84" BorderColor="#DEBA84" BorderStyle="None" BorderWidth="1px"
     DataKeyNames="PK_User" CellPadding="3" CellSpacing="2" DataSourceID="SqlDataSource6"
     OnRowDataBound="viewThemeTypeAssociationsGridView_OnRowDataBound">
     <Columns>
           <asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" />
           <asp:BoundField DataField="Name" HeaderText="Organization Team" SortExpression="Name" />
     </Columns>
     </asp:GridView>
     <asp:SqlDataSource ID="SqlDataSource6" runat="server" ConnectionString="<%$ ConnectionStrings:ApplicationServices %>"
                                            SelectCommand="
                                            SELECT [User].[PK_User]
                                                ,[User].[Name]
                                                ,[OrganizationalTeam].[Name]
                                            FROM [User]
                                            LEFT JOIN [OrganizationalTeam] ON [OrganizationalTeam].[PK_OrganizationalTeam] = [User].[OrganizationalTeamId]
                                            WHERE COALESCE(cast([OrganizationalTeam].[InternalExternal] as varchar(255)), 'null') LIKE @internalExternalParam
                                            GROUP BY [User].[Name]
                                                ,[OrganizationalTeam].[Name]
                                                ,[User].[PK_User]
                                            ">
    <SelectParameters>
          <asp:QueryStringParameter Name="internalExternalParam" DefaultValue="%" Type="String" />
    </SelectParameters>

我无法显示它。我认为它完成的方式如下:

<asp:BoundField DataField="[OrganizationalTeam].[Name]" HeaderText=" Team Name" SortExpression="[OrganizationalTeam].[Name]" />
<asp:BoundField DataField="[User].[Name]" HeaderText="Team" SortExpression="[User].[Name]" />

这导致以下错误:

User既不是DataColumn,也不是表DefaultView的DataRelation。

如何使用相同名称显示来自不同表的两列。

1 个答案:

答案 0 :(得分:6)

问题是这两列实际上都是Name,我的建议是在它们上使用别名来区分每个表中的数据:

SELECT [User].[PK_User]
    ,[User].[Name] as UserName
    ,[OrganizationalTeam].[Name] as OrganizationalTeamName
FROM [User]
LEFT JOIN [OrganizationalTeam] ON [OrganizationalTeam].[PK_OrganizationalTeam] = [User].[OrganizationalTeamId]
WHERE COALESCE(cast([OrganizationalTeam].[InternalExternal] as varchar(255)), 'null') LIKE @internalExternalParam
GROUP BY [User].[Name]
    ,[OrganizationalTeam].[Name]