Reputation: 1080
I am calling the server and returning a datatable of results but when I try to bind to the gridview, it is throwing an error about not being able to find a field or property on the data source. I'm newer to gridviews and .NET controls so any help would be appreciated.
The GridView
<asp:GridView ID="gv_Search" AutoGenerateColumns="false" runat="server" AllowSorting="true" OnSorting="gv_Search_Sorting">
<Columns>
<asp:HyperLinkField NavigateUrl="#" Text="View"/>
<asp:BoundField SortExpression="Hdefendant_name" HeaderText="Name" DataField="Hdefendant_name"/>
<asp:BoundField SortExpression="Hdefendant_location" HeaderText="Location" DataField="Hdefendant_location"/>
<asp:BoundField SortExpression="Hdate" HeaderText="Date Entered" DataField="Hdate"/>
</Columns>
</asp:GridView>
The Code-Behind for Gridview page (resultsList is a DataTable type)
var resultsList = defendantRepository.Search(start, end, name, location);
if (Defendant.hasRecords)
{
ViewState["PreliminaryInjunctions"] = resultsList.Columns;
gv_Search.DataSource = resultsList.Columns;
gv_Search.DataBind();
}
The Search (populates a DataTable and returns it to the variable resultsList from above) dv is a DefaultView and ds is a DataSet
using (var da = new SqlDataAdapter())
{
da.SelectCommand = cmd;
da.Fill(ds, "PreliminaryInjunctions");
}
dv = ds.Tables[0].DefaultView;
dt = dv.ToTable();
return dt;
Upvotes: 2
Views: 919
Reputation: 73313
The issue is I believe that you are binding the GridView to the Data Table's Columns
property:
gv_Search.DataSource = resultsList.Columns;
gv_Search.DataBind();
That property is of type DataColumnCollection
which does not contain names matching those defined in the BoundField
elements, and hence the error.
Instead bind to the DataTable itself:
gv_Search.DataSource = resultsList;
gv_Search.DataBind();
Upvotes: 1