使用 LINQ 数据绑定 gridview

发布于 2024-09-03 05:45:13 字数 4557 浏览 2 评论 0 原文

我有两个数据库表,一个用于网站的用户,包含字段“UserID”、“Name”和外键“PageID”。另一个包含字段“PageID”(此处为主键)和“Url”。

我希望能够在 gridview 中显示来自两个表的数据,并且我想在 aspx 页面中使用数据绑定来完成此操作。

不过,我不确定如何做到这一点,而且我找不到这种特殊情况的任何好的例子。到目前为止,这就是我所拥有的:

  <%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true"
    CodeBehind="Default.aspx.cs" Inherits="LinqBinding._Default" %>

<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
    <h2>
        Testing LINQ
    </h2>
    <asp:GridView ID="GridView1" runat="server" DataSourceID="LinqDataSourceUsers" AutoGenerateColumns="false">
        <Columns>
            <asp:CommandField ShowSelectButton="True" />
            <asp:BoundField DataField="UserID" HeaderText="UserID" />
            <asp:BoundField DataField="Name" HeaderText="Name" />
            <asp:BoundField DataField="PageID" HeaderText="PageID" />
            <asp:TemplateField HeaderText="Pages">
            <ItemTemplate
                <asp:DropDownList ID="DropDownList1"
                 DataSourceID="LinqDataSourcePages"
                 SelectedValue='<%#Bind("PageID") %>'
                 DataTextField="Url"
                 DataValueField="PageID"
                 runat="server">
                </asp:DropDownList>
            </ItemTemplate>
            </asp:TemplateField>           
        </Columns>
    </asp:GridView>
    <asp:LinqDataSource ID="LinqDataSourcePages" runat="server" 
    ContextTypeName="LinqBinding.UserDataContext" EntityTypeName="" 
        TableName="Pages">
    </asp:LinqDataSource>
    <asp:LinqDataSource ID="LinqDataSourceUsers" runat="server" 
        ContextTypeName="LinqBinding.UserDataContext" EntityTypeName="" 
        TableName="Users">
    </asp:LinqDataSource>
</asp:Content>

但这仅在将用户表放入网格视图(这不是问题)的情况下才有效,并且我将页面数据放入下拉列表中,但问题是:我当然得到了所有其中的页面数据,而不仅仅是每行上每个用户的页面。那么,如何在每一行的下拉列表中添加某种“位置”约束,以仅显示该行中用户的页面? (另外,说实话,我不确定我的外键关系是否正确,因为我不太习惯处理关系)。

编辑:

我认为我错误地建立了这种关系。我不断收到消息“Pages”不作为 User 对象上的属性存在。我想这是不可能的,因为现在的关系是一种方式。所以我尝试创建多对多关系。同样,我的数据库知识有点有限,但我添加了一个所谓的“连接表”,其中包含 UserID 和 PageID 字段,与其他表的主键相同。不过,我无法在连接表中创建这两个主键(看起来有些人在我见过的示例中拥有这些主键......但由于这是不可能的,所以我猜他们不应该这样做)。不管怎样,我从每个表创建了一个关系,并从中创建了新的 LINQ 类。

但那我该怎么办呢?我将联结表设置为 Linq 数据源,因为我猜想我必须这样做才能访问这两个表,但这不起作用。然后它抱怨该对象没有 Name 属性。那么如何访问相关表呢?

(顺便说一句:这是我寻找解决方案的一页:http://www.iaingalloway.com/2015/06/many-to-many-relationships-in-linq-to-sql.html ,但首先我不知道不明白他如何修改“Order”类代码隐藏,我只能进入上下文类(我无法按照他的建议在设计视图中右键单击该类并查看代码......),并且在那里没有。似乎没有任何方法可以引用联结类 - 在他的例子中为 Order_Details)...我错过了什么吗?)

这是我现在拥有的多对多关系:

 <%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true"
    CodeBehind="Default.aspx.cs" Inherits="ManyToMany._Default" %>

<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
    <h2>
        Many to many LINQ
    </h2>
    <asp:GridView ID="GridView1" runat="server" DataSourceID="LinqDataSource1" AutoGenerateColumns="false">
    <Columns>
        <asp:CommandField ShowSelectButton="True" />
        <asp:BoundField DataField="UserID" HeaderText="UserID" />
        <asp:BoundField DataField="Name" HeaderText="Name" />
        <asp:BoundField DataField="PageID" HeaderText="PageID" />
        <asp:TemplateField HeaderText="Pages">
        <ItemTemplate>
            <asp:DropDownList ID="DropDownList1"
             DataSource='<%#Eval("Pages") %>'
             SelectedValue='<%#Bind("PageID") %>'
             DataTextField="Url"
             DataValueField="PageID"
             runat="server">
            </asp:DropDownList>
        </ItemTemplate>
        </asp:TemplateField>           
    </Columns>
</asp:GridView>
    <asp:LinqDataSource ID="LinqDataSource1" runat="server" ContextTypeName="ManyToMany.UserPageDataContext"
        EntityTypeName="" TableName="UserPages">
    </asp:LinqDataSource>
</asp:Content>

I have two database tables, one for Users of a web site, containing the fields "UserID", "Name" and the foreign key "PageID". And the other with the fields "PageID" (here the primary key), and "Url".

I want to be able to show the data in a gridview with data from both tables, and I'd like to do it with databinding in the aspx page.

I'm not sure how to do this, though, and I can't find any good examples of this particular situation. Here's what I have so far:

  <%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true"
    CodeBehind="Default.aspx.cs" Inherits="LinqBinding._Default" %>

<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
    <h2>
        Testing LINQ
    </h2>
    <asp:GridView ID="GridView1" runat="server" DataSourceID="LinqDataSourceUsers" AutoGenerateColumns="false">
        <Columns>
            <asp:CommandField ShowSelectButton="True" />
            <asp:BoundField DataField="UserID" HeaderText="UserID" />
            <asp:BoundField DataField="Name" HeaderText="Name" />
            <asp:BoundField DataField="PageID" HeaderText="PageID" />
            <asp:TemplateField HeaderText="Pages">
            <ItemTemplate
                <asp:DropDownList ID="DropDownList1"
                 DataSourceID="LinqDataSourcePages"
                 SelectedValue='<%#Bind("PageID") %>'
                 DataTextField="Url"
                 DataValueField="PageID"
                 runat="server">
                </asp:DropDownList>
            </ItemTemplate>
            </asp:TemplateField>           
        </Columns>
    </asp:GridView>
    <asp:LinqDataSource ID="LinqDataSourcePages" runat="server" 
    ContextTypeName="LinqBinding.UserDataContext" EntityTypeName="" 
        TableName="Pages">
    </asp:LinqDataSource>
    <asp:LinqDataSource ID="LinqDataSourceUsers" runat="server" 
        ContextTypeName="LinqBinding.UserDataContext" EntityTypeName="" 
        TableName="Users">
    </asp:LinqDataSource>
</asp:Content>

But this only works in so far as it gets the user table into the gridview (that's not a problem), and I get the page data into the dropdown, but here's the problem: I of course get ALL the page data in there, not just the pages for each user on each row. So how do I put some sort of "where" constraint on dropdown for each row to only show the pages for the user in that row? (Also, to be honest I'm not sure I'm getting the foreign key relationship right, because I'm not too used to working with relationships).

EDIT:

I think I have set up the relationship incorrectly. I keep getting the message that "Pages" doesn't exist as a property on the User object. And I guess it can't since the relationship right now is one way. So I tried to create a many-to-many relationship. Again, my database knowledge is a bit limited, but I added a so called "junction table" with the fields UserID and PageID, same as the other tables' primary keys. I wasn't able to make both of these primary keys in the junction table though (which it looked like some people had in examples I've seen...but since it wasn't possible I guessed they shouldn't be). Anyway, I created a relationship from each table and created new LINQ classes from that.

But then what do I do? I set the junction table as the Linq data source, since I guessed I had to do this to access both tables, but that doesn't work. Then it complains there is no Name property on that object. So how do I access the related tables?

(BTW: Here's one page I looked at for finding a solution: http://www.iaingalloway.com/2015/06/many-to-many-relationships-in-linq-to-sql.html , but first of all I don't understand how he modifies the "Order" class codebehind. I can only get into the context class (I can't right-click the class in design view as he suggests and view code...), and in there there doesn't seem to be any way to refer to the junction class - Order_Details in his case)... Am I missing something?)

Here's what I have now with the many-to-many relationship:

 <%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true"
    CodeBehind="Default.aspx.cs" Inherits="ManyToMany._Default" %>

<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
    <h2>
        Many to many LINQ
    </h2>
    <asp:GridView ID="GridView1" runat="server" DataSourceID="LinqDataSource1" AutoGenerateColumns="false">
    <Columns>
        <asp:CommandField ShowSelectButton="True" />
        <asp:BoundField DataField="UserID" HeaderText="UserID" />
        <asp:BoundField DataField="Name" HeaderText="Name" />
        <asp:BoundField DataField="PageID" HeaderText="PageID" />
        <asp:TemplateField HeaderText="Pages">
        <ItemTemplate>
            <asp:DropDownList ID="DropDownList1"
             DataSource='<%#Eval("Pages") %>'
             SelectedValue='<%#Bind("PageID") %>'
             DataTextField="Url"
             DataValueField="PageID"
             runat="server">
            </asp:DropDownList>
        </ItemTemplate>
        </asp:TemplateField>           
    </Columns>
</asp:GridView>
    <asp:LinqDataSource ID="LinqDataSource1" runat="server" ContextTypeName="ManyToMany.UserPageDataContext"
        EntityTypeName="" TableName="UserPages">
    </asp:LinqDataSource>
</asp:Content>

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

请你别敷衍 2024-09-10 05:45:13

嗯,看来我自己找到了答案。本页解释了多对多关系和 LINQ 的问题:链接。使用该信息,我可以修改 User 类,以便它具有返回 IEnumerable 集合的属性。我将其添加到 User 类中(在 Linq 上下文的代码隐藏中):`

    public IEnumerable<Page> Pages
    {
        get { return UserPages.Select(u => u.Page); }
    }

这样我就可以拥有多对多关系,并且我可以直接引用 aspx 中的新 Pages 属性:

    <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="ManyToMany._Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:GridView ID="GridView2" runat="server" DataSourceID="LinqDataSourceUsers" AutoGenerateColumns="false">
            <Columns>
                <asp:CommandField ShowSelectButton="True" />
                <asp:BoundField DataField="UserID" HeaderText="UserID" />
                <asp:BoundField DataField="Name" HeaderText="Name" />
                <asp:TemplateField HeaderText="Pages">
                    <ItemTemplate>
                        <asp:DropDownList ID="DropDownList1" DataSource='<%#Eval("Pages") %>' DataTextField="Url"
                            runat="server">
                        </asp:DropDownList>
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
        </asp:GridView>
        <asp:LinqDataSource ID="LinqDataSourceUsers" runat="server" ContextTypeName="ManyToMany.UserPageDBDataContext"
            TableName="Users">
        </asp:LinqDataSource>
    </div>
    </form>
</body>
</html>

我希望这有帮助还有一个像我一样一直在为此苦苦挣扎的人!

Well, it seems I found the answer myself. This page explains the problems with many-to-many relationships and LINQ: Link. Using that information I could modify the User class so that it has a property to return an IEnumerable collection. I added this to the class User (in the codebehind for the Linq context):`

    public IEnumerable<Page> Pages
    {
        get { return UserPages.Select(u => u.Page); }
    }

That way I could have the many-to-many relationship, and I could simply refer to the new Pages property in the aspx directly:

    <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="ManyToMany._Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:GridView ID="GridView2" runat="server" DataSourceID="LinqDataSourceUsers" AutoGenerateColumns="false">
            <Columns>
                <asp:CommandField ShowSelectButton="True" />
                <asp:BoundField DataField="UserID" HeaderText="UserID" />
                <asp:BoundField DataField="Name" HeaderText="Name" />
                <asp:TemplateField HeaderText="Pages">
                    <ItemTemplate>
                        <asp:DropDownList ID="DropDownList1" DataSource='<%#Eval("Pages") %>' DataTextField="Url"
                            runat="server">
                        </asp:DropDownList>
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
        </asp:GridView>
        <asp:LinqDataSource ID="LinqDataSourceUsers" runat="server" ContextTypeName="ManyToMany.UserPageDBDataContext"
            TableName="Users">
        </asp:LinqDataSource>
    </div>
    </form>
</body>
</html>

I hope this helps someone else who has been struggling with this like I did!

太阳公公是暖光 2024-09-10 05:45:13

尝试将 DropDownList 数据源绑定到用户对象的 Pages 属性

<asp:GridView ID="GridView1" runat="server" DataSourceID="LinqDataSourceUsers" AutoGenerateColumns="false">
    <Columns>
        <asp:CommandField ShowSelectButton="True" />
        <asp:BoundField DataField="UserID" HeaderText="UserID" />
        <asp:BoundField DataField="Name" HeaderText="Name" />
        <asp:BoundField DataField="PageID" HeaderText="PageID" />
        <asp:TemplateField HeaderText="Pages">
        <ItemTemplate
            <asp:DropDownList ID="DropDownList1"
             DataSource='<%#Eval("Pages") %>'
             SelectedValue='<%#Bind("PageID") %>'
             DataTextField="Url"
             DataValueField="PageID"
             runat="server">
            </asp:DropDownList>
        </ItemTemplate>
        </asp:TemplateField>           
    </Columns>
</asp:GridView>

Try binding the DropDownList DataSource to Pages property of your user object

<asp:GridView ID="GridView1" runat="server" DataSourceID="LinqDataSourceUsers" AutoGenerateColumns="false">
    <Columns>
        <asp:CommandField ShowSelectButton="True" />
        <asp:BoundField DataField="UserID" HeaderText="UserID" />
        <asp:BoundField DataField="Name" HeaderText="Name" />
        <asp:BoundField DataField="PageID" HeaderText="PageID" />
        <asp:TemplateField HeaderText="Pages">
        <ItemTemplate
            <asp:DropDownList ID="DropDownList1"
             DataSource='<%#Eval("Pages") %>'
             SelectedValue='<%#Bind("PageID") %>'
             DataTextField="Url"
             DataValueField="PageID"
             runat="server">
            </asp:DropDownList>
        </ItemTemplate>
        </asp:TemplateField>           
    </Columns>
</asp:GridView>
晌融 2024-09-10 05:45:13

我之前在使用 ListView 和 LinqDataSources 时也遇到过类似的情况。我找到的唯一解决方案是在 OnRowCreated 或 OnRowDatabound 事件中设置 DropDownlist 的数据源。

您仍然可以将 LinqDataSource 用于 BoundFields,但我怀疑您可能需要在这种情况下在后面的代码中执行 TemplateField。

代码:

<asp:GridView ID="GridView1" runat="server" OnRowCreated="GridView1_OnRowCreated" DataSourceID="LinqDataSource1" AutoGenerateColumns="false">
<Columns>
    <asp:CommandField ShowSelectButton="True" />
    <asp:BoundField DataField="UserID" HeaderText="UserID" />
    <asp:BoundField DataField="Name" HeaderText="Name" />
    <asp:BoundField DataField="PageID" HeaderText="PageID" />
    <asp:TemplateField HeaderText="Pages">
    <ItemTemplate>
        <asp:DropDownList ID="DropDownList1"
         DataSource='<%#Eval("Pages") %>'
         SelectedValue='<%#Bind("PageID") %>'
         DataTextField="Url"
         DataValueField="PageID"
         runat="server">
        </asp:DropDownList>
    </ItemTemplate>
    </asp:TemplateField>           
</Columns>

C#:

protected void GridView1_OnRowCreated(object sender, EventArgs e)
{
   //Create int variable with the UserId value
   //Create new Linq query to be used as datasource.  must get pages and filter by userid.
   //FindControl DropDownList1
   //use the linq query mentioned in the second comment  as the datasource for DropDownList1
   //DataBind DropDownList1

   //Example: 
int userId = /*get userid logic*/;
var userPages = from t in dc.Pages
                where t.UserId = userId
                select t;
((DropDownList)/*Find drop down list*/).DataSource = userPages;
((DropDownList)/*Find drop down list*/).DataBind()
}

I've run into similar situations before with a ListView and LinqDataSources. The only solution i've found is to set the datasource for the DropDownlist in the OnRowCreated or OnRowDatabound events.

You can still use the LinqDataSource for your BoundFields but I suspect you might need to do the TemplateField in the code behind in this case.

Code:

<asp:GridView ID="GridView1" runat="server" OnRowCreated="GridView1_OnRowCreated" DataSourceID="LinqDataSource1" AutoGenerateColumns="false">
<Columns>
    <asp:CommandField ShowSelectButton="True" />
    <asp:BoundField DataField="UserID" HeaderText="UserID" />
    <asp:BoundField DataField="Name" HeaderText="Name" />
    <asp:BoundField DataField="PageID" HeaderText="PageID" />
    <asp:TemplateField HeaderText="Pages">
    <ItemTemplate>
        <asp:DropDownList ID="DropDownList1"
         DataSource='<%#Eval("Pages") %>'
         SelectedValue='<%#Bind("PageID") %>'
         DataTextField="Url"
         DataValueField="PageID"
         runat="server">
        </asp:DropDownList>
    </ItemTemplate>
    </asp:TemplateField>           
</Columns>

C#:

protected void GridView1_OnRowCreated(object sender, EventArgs e)
{
   //Create int variable with the UserId value
   //Create new Linq query to be used as datasource.  must get pages and filter by userid.
   //FindControl DropDownList1
   //use the linq query mentioned in the second comment  as the datasource for DropDownList1
   //DataBind DropDownList1

   //Example: 
int userId = /*get userid logic*/;
var userPages = from t in dc.Pages
                where t.UserId = userId
                select t;
((DropDownList)/*Find drop down list*/).DataSource = userPages;
((DropDownList)/*Find drop down list*/).DataBind()
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文