2011-05-01 80 views
0

我需要将LINQ查询绑定到gridview的行。我正在试图创建一个像expedia中的矩阵那样的表,其中不停地在不同的行上停止和停止两次。我不太确定如何将查询绑定到gridview行。我感谢您的帮助。gridview行绑定到linq查询

var imgquery = from f in XElement.Load(MapPath("flightdata3.xml")).Elements("flight") 
        orderby Convert.ToInt32(f.Element("price").Value) 
        select new 
        { 
         ImagePath = (string)f.Element("airlineimageurl").Value 
        }; 


    //query for gvMatrix where numberofstops=0 
    var numstops0query = from f in XElement.Load(MapPath("flightdata3.xml")).Elements("flight") 
       where Convert.ToInt32(f.Element("numberofstops").Value) == 0 
       orderby Convert.ToInt32(f.Element("price").Value) 
       select new 
       { 
        Price = "$" + (Int32)f.Element("price"), 
        ImagePath = (string)f.Element("airlineimageurl").Value 
       }; 

    <asp:GridView ID="gvMatrix" runat="server"> 
    </asp:GridView> 
+0

你的意思是说每一行都要绑定不同的数据集? – mehul9595 2011-05-01 14:59:33

+0

请提供一些你想要做的代码示例 – Andre 2011-05-01 15:00:54

+0

我的意思是每一行都会绑定到不同的查询。这是否有意义?每行都会有不同的条件,比如不停止= 0,不停止= 1,不停止= 2 – multiv123 2011-05-01 15:01:01

回答

0

我相信你会需要从GridView的RowDataBound事件打电话给你二次查询,然后手动填充您的第二个值字段:

http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.rowdatabound.aspx

然而,似乎你也许能在SQL连接或子选择中获得你正在寻找的东西。如果您使用的是SQL数据源,那么我会使用SQL来查看是否可以在单个Select语句中获取数据,然后返回并查看是否可以将SQL查询转换为适当的LINQ - 或者我可能会调用它通过一个存储过程。但是,如果您致力于LINQ,或者如果加入或子选择不行,那么RowDataBound是您最好的选择。

+0

嗨,我正在考虑使用RowDataBound。我去了那个链接,但仍然不确定如何将LINQ查询绑定到RowDataBound事件 – multiv123 2011-05-01 16:40:04

+0

你真的不能“绑定”查询。您手动执行它并将值放入网格行。当为每行触发RowDataboundEvent时,您需要获取需要的行值以标识当前行/参数,然后执行LINQ查询以检索行特定的结果。最后,您使用显示的语法(e.Rows.Cells)将结果放在适当的列中。这是一个更深入的例子。它不会为每一行查询,但会显示其他操作。 http://www.simple-talk.com/dotnet/asp.net/take-row-level-control-of-your-gridview/ – 2011-05-01 16:58:56

0

我不确定,网格视图会给你所需的功能,因为数据集将绑定到整个网格。您可以在运行时创建HTMl表结构,并且您创建的每一行都可以控制它,以绑定您拥有的任何linq数据。希望它有帮助:)

placeHolder.Controls.Clear(); //asp:placeholder holds the table structure. 
Table table = new Table(); 
table.ID = "table"; 
placeHolder.Controls.Add(table); //adding to place holder 

TableRow row = new TableRow(); 
row.ID ="rowID"; 
table.Rows.Add(row); //creating first row for first linq dataset 

var nonstop0query = from x in obj select new {x.ID, x.Name, x.Age}; //first linq dataset. 

//Creating cells for the data returned by the nonstop0query 
TableCell cell = new TableCell(); 
cell.ID = "cell1"; 
row.Cells.Add(cell); 
cell.Text = nonstop0Query[0]; 

cell = new TableCell(); 
cell.ID = "cell2"; 
row.Cells.Add(cell); 
cell.Text = nonstop0Query[1]; 

cell.ID = "cell3"; 
row.Cells.Add(cell); 
cell.Text = nonstop0Query[2]; 

//Same way can be done for more dataset to bind to row. 
+0

还不知道该怎么做。你能指点我一些示例代码吗? – multiv123 2011-05-01 16:30:42

+0

嗨,我有麻烦的代码行: cell.Text = nonstop0Query [0]; – multiv123 2011-05-02 16:09:17

+0

这是我只是代表返回的属性,即ID,名称和年龄。如果你得到的非停顿0查询数> 1,那么你将不得不迭代它,否则你可以做nonstop0query.ID等等...这个代码只是伪。 :) – mehul9595 2011-05-03 07:59:25