简体   繁体   中英

Pass variable to sqldatasource Select command client side

I have a grid and a dropdownlist from where the user select the query to fill in the grid. As it is now it works fine:

protected void Button1_Click(object sender, EventArgs e)
    {
        string selected = DropDownList1.SelectedItem.Value;
        if (selected == "0")
        {
            Label1.Text = "You shall select a query!";
        }
        else
        {
            int x = Int32.Parse(selected);
            string query = "";
            switch (x)
            {
                case 1:     //Top 100 TB 321
                    query = @"...something...";
                    SqlDataSource1.SelectCommand = query;
                    break;

                case 2:
                    query = @"....something else....";
                    SqlDataSource1.SelectCommand = query;
                    break;

                case 3:     
               .......
            }
        }

And in the markup I simply have the sqldatsource with the connection string:

 <asp:SqlDataSource ID="SqlDataSource1" runat="server"
         ConnectionString="<%$ ConnectionStrings:BOMConnectionString %>" 
         ></asp:SqlDataSource>

With the above code I am unable to export the content of the grid because it generate an error "Object reference not set to an instance of an object". To avoid this issue, instead of defining the select command from code behind, I should pass the query as variable to the sqldatasource in the markup. How can I pass the variable "query" to the sqldatasource SelectCommand in the markup?

If the "export" feature is also a callback from the web application, you should be able to see the state of DropDownList1 in the callback. Use that to set the SelectCommand as in your code above. (I recommend moving the duplicated code into its own helper function so that if you call it from multiple places you don't have to change them all if you edit the functionality later).

Alternatively, but the SqlDataSource in session storage on the server, rather than pretending it's part of the web page. Then when you set its SelectCommand, that value will be remembered across callbacks.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM