简体   繁体   中英

Convert list result to datatable using linq?

Convert list result to datatable using linq?

I am getting below error but candidate ID is there in my datatable result.

A field or property with the name 'Candidate ID' was not found on the selected data source.

Below is my code. I am trying to bind result datat to gridview but error is coming.

    var m_strFilePath = "webserviceurl";

    string xmlStr;
    using (var wc = new WebClient())//using Web client downloading xml string  from WEB API
    {
        xmlStr = wc.DownloadString(m_strFilePath);
    }
    DataSet ds = new DataSet();
    ds = ConvertXMLToDataSet(xmlStr);
    DataTable dt = new DataTable();
    dt = ds.Tables["FL"];



 List<DataTable> result = dt.AsEnumerable().Where(x => x.Field<int>("row_Id") == 0)
     .GroupBy(x => x.Field<int>("row_Id"))
     .Select(grp => grp.CopyToDataTable())
     .ToList();
       GridView1.DataSource = result;
       GridView1.DataBind();

Below is gridview design code.

 <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" GridLines="None" CssClass="table table-bordered table-striped" Width="100%" >
     <Columns>
         <asp:BoundField DataField="Candidate ID" HeaderText="Id" />

         <asp:TemplateField HeaderText="Action">
             <ItemTemplate>
                 <asp:LinkButton ID="lnkbtn_viewdetails" runat="server" OnClick="lnkbtn_viewdetails_Click" CssClass="btn bg-light-blue-active">View Details</asp:LinkButton>
             </ItemTemplate>
         </asp:TemplateField>
     </Columns>
     <EmptyDataTemplate>
         <span style="color: red; font-size: 18px; font-weight: 600; text-align: center; padding-left: 355px;">No records for the entered search details </span>
     </EmptyDataTemplate>
 </asp:GridView>

below is result datatable data.

在此处输入图片说明

I think your linq query will return a list of DataRow not DataTable . So I think it should be List<DataRow> result = ...

Then:

DataTable newDt = new DataTable();

For(i = 0; i < result.count; i++)
    newDT.add(result[i]);

Then set the DataGridView

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM