Update FilterParameter values programmatically?

1.7k Views Asked by At

How can I update filter parameter values of a SQLDataSource whom filter expression & filter parameter have already been defined in aspx? I am trying to add an alpha pager.

Code behind

protected void rptFilterUI_ItemCommand(object source, RepeaterCommandEventArgs e)
{
    if (e.CommandName == "All")
    {
        ClearFilter();
    }
    else
    {
        userSource.FilterParameters.Clear();
        userSource.FilterParameters[0].DefaultValue = "LOGINID";
        userSource.FilterParameters[1].DefaultValue = e.CommandName;
        userSource.DataBind();
    }
}

ASPX

<asp:SqlDataSource ID="userSource" runat="server" ProviderName="System.Data.OleDb"
    ConnectionString="<%$ connectionstrings:testApp%>" SelectCommand="select * from foo"
    FilterExpression="CONVERT({0},'System.String') like '{1}%'" EnableCaching="false">
    <FilterParameters>
        <asp:ControlParameter Name="test2" ControlID="SearchByDropDownList" PropertyName="SelectedValue" />
        <asp:ControlParameter Name="test" ControlID="SearchTextBox" PropertyName="text" />
    </FilterParameters>
</asp:SqlDataSource>

It throws index out of range

Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index

1

There are 1 best solutions below

0
On

FilterParameters is a collection. Therefore this statement...

userSource.FilterParameters.Clear()

...will truncate the list of filter paremeters. So, if you try to reference a member of an empty collection, you will get a index out of range exception.

Try this...immediately after .Clear(), place the following code..

userSource.FilterParameters.Add(new ControlParameter("test2", "SearchByDropDownList", "SelectedValue"));            
userSource.FilterParameters.Add(new ControlParameter("test", "SearchTextBox", "Value"));