簡體   English   中英

將LINQ to XML填充到Grdiview

[英]populate LINQ to XML to Grdiview

我正在嘗試使用LINQ填充GridView。 我的XML看起來像這樣:

      <?xml version="1.0" ?> 
- <!-- Created @ 9/14/2011 1:16:52 PM
  --> 
- <DoctorList>
- <Doctor ID="1" Specialist="Dentist">
  <Username>Ahmed</Username> 
  <Password>12345</Password> 
  </Doctor>
- <Doctor ID="2" Specialist="oculist">
  <Username>Aya</Username> 
  <Password>12345</Password> 
  </Doctor>
- <Doctor ID="3" Specialist="surgery">
  <Username>malak</Username> 
  <Password>12345</Password> 
  </Doctor>
  </DoctorList>

我正在使用以下代碼:

IEnumerable<XElement> matches = from Doctor in doc.Descendants("Doctor") where (int)Doctor.Attribute("ID") > 1 select Doctor;
GridView1.DataSource= matches;
       GridView1.DataBind();

這將返回一個錯誤,即找不到“專家”列。 我想顯示專家,id屬性和所有內部元素。 我的gridview就像這樣:

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"  
            CellPadding="4" HeaderStyle-BackColor="blue" HeaderStyle-ForeColor="White" 
            HeaderStyle-HorizontalAlign="Center" HeaderStyle-Font-Bold="True" 
            ondatabound="GridView1_DataBound">
            <Columns>  
            <asp:BoundField HeaderText="Specialist" DataField="Specialist" /> 
            <asp:BoundField HeaderText="ID" DataField="ID" ItemStyle-HorizontalAlign="Right" />
            <asp:BoundField HeaderText="Username" DataField="Username" ItemStyle-HorizontalAlign="Right" />
            <asp:BoundField HeaderText="Password" DataField="Password" ItemStyle-HorizontalAlign="Right" />
             </Columns>

<HeaderStyle HorizontalAlign="Center" BackColor="Blue" Font-Bold="True" ForeColor="White"></HeaderStyle>
           </asp:GridView>

我還確保matches返回值。

嘗試

IEnumerable<XElement> matches = 
               from Doctor in doc.Descendants("Doctor") 
               where (int)Doctor.Attribute("ID") > 1 
               select new {
                              Specialist = Doctor.Attribute("Specialist").Value,
                              ID = Doctor.Attribute("ID").Value,
                              Username = Doctor.Element("Username").Value,
                              Password = Doctor.Element("Password").Value
                };

GridView1.DataSource = matches;
GridView1.DataBind();

您將無法按原樣使用xml-GridView要求將所有內容組織為屬性。 正確的架構如下所示:

<DoctorList>
    <Doctor ID="1" Specialist="Dentist" UserName="Ahmed" Password="12345" />
    <Doctor ID="2" Specialist="oculist" Username="Aya" Password="12345" />
    <Doctor ID="3" Specialist="surgery" Username="malak" Password="12345" />
</DoctorList>

我將按照以下步驟解決您的問題:

  1. 采取上述示例XML塊,並將其與GridView一起使用。

  2. 如果您不能一開始就控制生成方式,請轉換傳入的Xml以匹配該模式。 這里有一些關於如何做到這一點從谷歌的文章...... 這里是一個。

祝好運。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM