Search code examples
c#asp.netfilterwebformsobjectdatasource

Filtering an ASP.NET ObjectDataSource?


I have a ObjectDataSource in a standard ASP.NET WebForm which allows effective paging by only loading the data required for the page the user is viewing. I now want to filter the results on specific columns (say column Customer), how would you go about this?

<asp:ObjectDataSource ID="ticketsDataSource" runat="server"
        SelectMethod="GetTicketsData" EnablePaging="true"
        MaximumRowsParameterName="pageSize"
        StartRowIndexParameterName="startRowIndex"
        TypeName="SupportSystem.App_Code.TicketsDataSource" SelectCountMethod="TotalRowCount">
        <SelectParameters>
            <asp:Parameter Name="startRowIndex" Type="Int32" />
            <asp:Parameter Name="pageSize" Type="Int32" />
        </SelectParameters>
</asp:ObjectDataSource>

I was previously doing everything in code behind as follows, but this meant once numerous tickets were added, the grid was very slow when paging etc as it was loading all the data before rendering etc.

DataSet ds = new DataSet();
Dictionary<string, object> d = new Dictionary<string, object>();
d.Add("@params", "");
ds.ReadXml(new System.IO.StringReader(Database.DAL_XML("Usp_Fetch_Tickets", d).OuterXml));
if (Database_error(ds))
{
   return;
}
var dv = ds.Tables[0].DefaultView;
dv.RowFilter = "Customer LIKE '%abc%'";
var newDS = new DataSet();
var newDT = dv.ToTable();
newDS.Tables.Add(newDT);
gvTickets.DataSource = newDS;
gvTickets.DataBind();

Any ideas of how to effectively filter the ObjectDataSource?


Solution

  • Hi You can use FilterExpression for that purpose. Following is the sample snippet how to achieve that.

    <asp:objectdatasource
              id="ObjectDataSource1"
              runat="server"
              selectmethod="GetAllEmployeesAsDataSet"
              typename="Samples.AspNet.CS.EmployeeLogic"
              filterexpression="FullName='{0}'" OnFiltering="ObjectDataSource1_Filtering">
                <filterparameters>
                  <asp:formparameter name="FullName" formfield="Textbox1" defaultvalue="Nancy Davolio" />
                </filterparameters>
            </asp:objectdatasource>
    

    Additional info can be found on the following msdn page check this link