为一个数据网格视图设置两个数据源 ASP.NET C#

问题描述 投票:0回答:1

我想对我的单个数据网格视图使用两个数据源

<asp:GridView ID="GridView1" runat="server" OnRowDataBound="GridView1_RowDataBound">
    <Columns>
        <asp:BoundField DataField="BasSaat" HeaderText="BasSaat" />
        <asp:BoundField DataField="Ad" HeaderText="Ad" />
    </Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource2" runat="server" ConnectionString="<%$ ConnectionStrings:RemoteConnect %>" SelectCommand="SELECT [Name] FROM [Table1]"></asp:SqlDataSource>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:RemoteConnect %>" SelectCommand="SELECT [Country] FROM [Table2]"></asp:SqlDataSource>`

这是我背后的代码:

    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            // Set the value of the first BoundField to use SqlDataSource1
            e.Row.Cells[0].Text = ((DataRowView)e.Row.DataItem)["Name"].ToString();

            // Set the value of the second BoundField to use SqlDataSource2
            e.Row.Cells[1].Text = ((DataRowView)e.Row.DataItem)["Country"].ToString();
        }
    }

但是我的网格视图是空的。有两个不同的数据源怎么办?

请不要告诉我应该使用存储过程并使用 inner join 什么的。

我的问题不一样,更喜欢这样简单地问

根本不可能使用一个数据源

而且我必须在 Visual Studio 中而不是在 SQL Server 中选择我的问题。

谢谢

c# asp.net sql-server gridview datasource
1个回答
1
投票

你有几件事在这里发生,那是关闭的。

首先,一个数据网格只能关联一个数据源。这是一个硬性要求。

其次,您必须将有关数据源的信息告知 DataGrid,以便绑定起作用。我通常在后面的代码上使用代码来执行此操作,因此我不必在 ASPX 端使用 DataSource 对象,但这超出了问题的范围。要让 DataGird 查看 DataSource,您必须设置其 DataSourceId 属性。

<asp:GridView ID="GridView1" runat="server" DataSourceID="SqlDataSource1">
<Columns>
    <asp:BoundField DataField="Name" HeaderText="Name" />
    <asp:BoundField DataField="Country" HeaderText="Country" />
</Columns>
</asp:GridView>

第三,因为您使用的是 BoundFields,所以不需要尝试设置值的代码隐藏函数。 DataField 属性处理这个问题。所以你可以删除对 RowDataBound 事件处理程序的引用(我在上面的代码中这样做)

最后,您必须弄清楚如何将两个数据集连接到一个查询中。 [Table1] 和 [Table2] 之间应该存在关系,以了解它们之间的关系。因为我不知道,所以我使用了 CROSS JOIN(将表 1 中的每个名称连接到表 2 中的每个国家/地区)在下面的数据源中创建了一个数据集,这也是您想要看到的内容的含义两个独立的 DataSource 对象。

<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:RemoteConnect %>" SelectCommand="SELECT t1.[Name], t2.[Country] FROM [Table1] t1 CROSS JOIN [Table2] t2"></asp:SqlDataSource>
© www.soinside.com 2019 - 2024. All rights reserved.