Thursday, February 12, 2009

ObjectDataSource - Selectcount method with custom parameters and custom paging.

On one of my project i was using ObjectDataSource with several parameters. I had a business logic layer with a method (For eg. GetProducts) which returns the actual recordset to be displayed also i had some logic to calculate the total records within the same method and i was populating a private member. I had a separate method to return the count from the private member and this method takes no parameter.


For e.g.

public class ProductLogic
{
  private int rowCount;
  public IList<Product>GetProducts(string filter, int maxRows, int startIndex)
  {
    ...
    ...
  rowCount = 'logic to populate the count
  }
  public int GetProductCount()
  {
    return rowCount;
  }
}


My ObjectDataSource declaration is...




<asp:ObjectDataSource ID="ObjectDataSource1" runat="server"

SelectMethod="GetProducts"
TypeName="ProductLogic" SelectCountMethod="GetProductCount" EnablePaging="true"
OnSelecting="Obds_Selecting"
SortParameterName="sortExpression"
>


The problem i was facing was whenever objectdatasource makes a call to the "GetProductCount" method it was expecting me to pass all the parameters like "GetProducts". I did a Google Search but i couldn't find any information. So I did the following working around,

There is a ExecutingSelectCount property you can use to decide whether the ObjectDataSource is getting the list or the count. So using this property whenever it makes call to your count method just clear out your inputparameter collection and you should be good to go. So my CodeBehind looks like this...


protected void obds_Selecting(object sender, ObjectDataSourceSelectingEventArgs e)
{
  if (!e.ExecutingSelectCount)
  {
    e.InputParameters["filter"] = ....;
  }
  else
  {
    e.InputParameters.Clear();
  }
}

Let me know if you still have any issues i will try my best to answer it.


No comments:

Post a Comment