I want to create GridView and its columns dynamically according to the datatable returned. So, I returned the datatable to the aspx file through ViewData and iterate the columns of datatable to create a GridView template. Then, using C# in aspx to bind the datatable to the GridView. But when I try to get the GridView in the aspx file, error message "The name XXX does not exist in the current context" is displayed. Any other way to achieve what I want to do?
The followings are my source code:
Controller
public ActionResult gridViewPage() {
DataTable dt = runSqlQueryToReturnADataTable();
ViewData["DT"] = dt;
ViewData["DisplayMode"] = "Grid";
return View();
}
ASPX File
<% if ("Grid".Equals(ViewData["DisplayMode"])) { %>
<asp:GridView ID="gridViewForQuery" runat="server">
<Columns>
<% foreach (System.Data.DataColum col in (ViewData["DT"] as System.Data.DataTable).Columns) %>
<asp:BoundField DataField="<%: col.ColumnName %>"/>
</Columns>
</asp:GridView>
<% gridViewForQuery.DataSource = (ViewData["DT"] as System.Data.DataTable); gridViewForQuery.DataBind(); %>
<% } %>