I want to set a parameter for a SqlDataSource programmatically as described in Step 5 at http://www.asp.net/data-access/tutorials/using-parameterized-queries-with-the-sqldatasource-vb . Also a GridView is bound to the sqlDataSource. My markup is:
<asp:SqlDataSource ID="mySqlDataSource" runat="server"
ConnectionString="<%$ ConnectionStrings:ConnectionStringHTL %>"
SelectCommand="SELECT [subscription_con] FROM [HTL_CONSUME_CON] WHERE ([subscription_con] = @subscription_con)">
<SelectParameters>
<asp:Parameter Name="subscription_con" Type="Int32" />
</SelectParameters>
</asp:SqlDataSource>
<asp:GridView ID="myGridView" runat="server" AllowPaging="True"
AllowSorting="True" DataSourceID="mySqlDataSource">
</asp:GridView>
In the codebehind, I have:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
mySqlDataSource.SelectParameters("subscription_con").DefaultValue = calcResult()
End Sub
The return value from calcResult() is different for each postback. The postback occurs when the user clicks a Button on the form that has UseSubmitBehavior=True.
I've use the debugger to step through the code behind and I see it executed for each page load and I see the expected values returned from clacResult().
However the bound DataGrid is never updated on the postbacks, it only updates on the first page load.
If I change the SqlDataSource parameter to have a control as the source, then it works on postbacks. In otherwords, I changed the markup to use:
<asp:ControlParameter ControlID="myTextBox" Name="subscription_con" PropertyName="Text" Type="Int32" />
and I changed the code behind to be:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
myTextBox.Text = calcResult()
End Sub
With the TextBox control as the source of the SqlDataSource parameter, update of the GridView works for the original page load and all postbacks. However, I really have no need for the TextBox and would prefer not to use it.
What am I missing about how to set a parameter programmatically for an SqlDataSource? Why doesn't the bound GridView get updated on postbacks when setting the SqlDataSource parameter programmatically when there is no control source?
You may need an explict databaind on postbacks:
if (Page.IsPostBack)
{
grid.DataBind();
}
Should do it.