0

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(); %>
<% } %>
Code Chewer
  • 41
  • 1
  • 4
  • You can directly set datatable and set AutoGeneratedColumn=True of GridView then it will automatically create columns that Database has. – Kevin Shah Mar 14 '17 at 07:37

1 Answers1

0

if you define grid depend any condition , you can not access from codebehind.

change gridview definition to this.

<% if ("Grid".Equals(ViewData["DisplayMode"])) {
   gridViewForQuery.DataSource = (ViewData["DT"] as System.Data.DataTable); gridViewForQuery.DataBind();
 }%>
<asp:GridView ShowHeaderWhenEmpty="false" AutoGenerateColumns="true" ID="gridViewForQuery" runat="server">

</asp:GridView>
levent
  • 3,464
  • 1
  • 12
  • 22
  • Thank you for your reply. Your solution does solve the problem! But another problem arise. Error message "Control 'gridViewForQuery' of type 'GridView' must be placed inside a form tag with runat=server." Does it mean that I can only assign datasource and bind data at code behind? Any other solution? Thank you! – Code Chewer Mar 14 '17 at 08:03
  • I updated post. and check this for runat="server" error. http://stackoverflow.com/a/21554229/4172872 – levent Mar 14 '17 at 08:53