Friday, March 30, 2012

How to control the loading of SqlDataSource?

I have an SqlDatSource that I have fully setup at design time, but I don't want it to open and load as soon as the page loads, instead I want to open it based on a condition.

How do you do that with a DataSource?

I know that I can simply remove the Select query, and then set it at run time, but I'm looking for something better, that allows me to have the Select query set at design time, in part because I have a lot of parameters.

Usually you have a control such as GridView or DetailsView that is connected to the SqlDataSource through its DataSourceId attribute. This will cause it to execute the query. If you leave the attribute empty the query will not be executed. From code you can set the DataSource and then call DataBind(). That will cause the SqlDataSource to execute:

GridView1.DataSource = SqlDataSource1;GridView1.DataBind();// Now the query is executed
|||

Within the SqlSataSource.Selecting event, you will have access to the Cancel property which you can set based on your conditions. If Cancel is set to True, then the Select event will not occur.

|||

while michielvoo's way is probably better, another way you can get the date to not display is to just set the GridView's Visible="false" initially, if you want the datasourceID property of the sqldatasource to be defined in the contol creation. Then, in your button_click event or whatever you do to get the data, you do:

VB:

GridView1.DataBind()
GridView1.Visible = True

C#:

GridView1.DataBind();
GridView1.Visible = True;

No comments:

Post a Comment