Ye Myat Aung
Ye Myat Aung

Reputation: 1853

Gridview is not displaying data with code-behind sqldatasource

I have gridview and its binded with datasource which is created in the code behind file. And I needed to enable sorting and paging in the easiest way so I wrote as following -

In button's click event

SqlDataSource dataSource = new SqlDataSource(ConfigurationManager.ConnectionStrings["connstr"].ConnectionString, searchQuery);
        dataSource.SelectCommandType = SqlDataSourceCommandType.Text;
        dataSource.SelectCommand = searchQuery;
        if (txtSearchQuery.Text != "")
        {
            dataSource.SelectParameters.Add("searchQuery", txtSearchQuery.Text);
        }
        gridBookings.DataSourceID = dataSource.ID;

However, when the button was clicked, the gridview wasn't populated with data. Any ideas?

Upvotes: 0

Views: 2907

Answers (3)

Davide Piras
Davide Piras

Reputation: 44605

difficult to say without seeing your full page markup and code behind.

In general after associating the DataSource you should also call:

gridBookings.DataBind();

Upvotes: 0

Eric Herlitz
Eric Herlitz

Reputation: 26257

you must databind

...
gridBookings.DataSourceID = dataSource.ID;
gridBookings.DataBind();

Although I'd prefer this approach

...
gridBookings.DataSource = dataSource;
gridBookings.DataBind();

Upvotes: 0

Massimiliano Peluso
Massimiliano Peluso

Reputation: 26727

you forgot to call DataBind on the grid:

gridBookings.DataBind();

Upvotes: 3

Related Questions