Search code examples
asp.netlistviewsqldatasource

is there a way to have a sqldatasource filter when asked but default to select *?


I have a listview that is bound to a sqldatasource. I know how to filter the results by binding the sqldatasourceto a control value, but I want the sqldatasource to select all when nothing in the control is selected. How do i do that?

Keep in mind that i have the listview paged as I know this can pose problems to simple solutions. For instance, if I handle the initial load with !Page.IsPostback, the initial contents of the list is fine, but if I click on a page in the pager control, it will reload the grid with whatever name is selected in the filter dropdown.


Solution

  • You can use the SqlDataSource Selecting event to modify parameters before the select command gets executed.

    C#

       protected void SqlDataSource1_Selecting(object sender, SqlDataSourceSelectingEventArgs e)
        {
            if (DropDownList1.SelectedValue != "thisValue")
            {
                // Do what you want with the datasource here. In the example I change the
                // value of a parameter
                e.Command.Parameters["@parameter"].Value = DropDownList1.SelectedValue;
            }
        }
    

    VB

    Protected Sub SqlDataSource1_Selecting(sender As Object, e As SqlDataSourceSelectingEventArgs)
        If DropDownList1.SelectedValue <> "thisValue" Then
            e.Command.Parameters("@parameter").Value = DropDownList1.SelectedValue
        End If
    End Sub
    

    Here's the MSDN article on SqlDataSource.Selecting Event