How to fill gridView wihtout actually knowing any of the fields

I have this query select distinct b.Name Project, a.Name Field from viewBatchClassIndexFields a inner join BatchDef b on a.DocumentBatchDefID = b.BatchDefID where b.Name = @projecto order by 1

What this does is, grabs the projectName and with that it return indexFields that are needed the catch is that almost every projectName as different index fields as a return, my question is.
How can i populate a gridView without knowing before hand what fields i will have.

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

there is nothing stopping you from having the gridview auto generate the columns for you. In fact, if you do nothing, that is the default!!!

So, I assume you used the project->settings, and setup a valid connection to the database. Ok, so now we drop a gridview onto the web page, say like this:

        <asp:GridView ID="GridView1" runat="server"></asp:GridView>

ok, now, here is our code to fill the grid view:

  protected void Page_Load(object sender, EventArgs e)
        if (!IsPostBack)

    void LoadGrid()
        // load up our grid
        using (SqlCommand cmdSQL = new SqlCommand("SELECT TOP 10 * from tblHotels ORDER BY HotelName ",
            new SqlConnection(Properties.Settings.Default.TEST4)))
            GridView1.DataSource = cmdSQL.ExecuteReader();

So, no where did I specify any column names.


How to fill gridView wihtout actually knowing any of the fields

So, you can shove/use/have any query you want in above – the grid will use the column names from the data source. As a result, you can quite much use any data source (any sql query – even ones with joins) for that data source.

You can also of course load the query results into a datatable, and then of course loop the column names, and add them to the columns to the gridview, but if you don’t set AutoGeneraateColumns = false (then the grid will auto generate columns for you).

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from or, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply