Бөлісу құралы:


ObjectDataSource.SelectCountMethod Свойство

Определение

Возвращает или задает имя метода или функции, вызываемой ObjectDataSource элементом управления для получения количества строк.

public:
 property System::String ^ SelectCountMethod { System::String ^ get(); void set(System::String ^ value); };
public string SelectCountMethod { get; set; }
member this.SelectCountMethod : string with get, set
Public Property SelectCountMethod As String

Значение свойства

Строка, представляющая имя метода или функции, которая ObjectDataSource используется для получения количества строк. Метод должен возвращать целое число (Int32). Значение по умолчанию — пустая строка ("").

Примеры

В следующих трех примерах показана веб-страница, класс страницы программной части и класс доступа к данным, позволяющий пользователю выбрать количество записей, отображаемых на странице.

Веб-страница содержит ObjectDataSource элемент управления, для свойства которого EnablePaging задано trueзначение . Для SelectCountMethod свойства задано имя метода, возвращающего общее количество записей в запросе. Свойство MaximumRowsParameterName и StartRowIndexParameterName свойство задаются именами параметров, используемых в методе Select. Страница также содержит DropDownList элемент управления.

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>ObjectDataSource Example</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    How many rows to display on this page:<br />
    <asp:DropDownList 
          AutoPostBack="true" 
          ID="rowsToDisplay" 
          runat="server" 
          onselectedindexchanged="rowsToDisplay_SelectedIndexChanged">
        <asp:ListItem Value="5"></asp:ListItem>
        <asp:ListItem Value="10" Selected="True"></asp:ListItem>
        <asp:ListItem Value="20"></asp:ListItem>
    </asp:DropDownList> 
    
    <asp:ObjectDataSource 
        SelectCountMethod="GetEmployeeCount" 
        EnablePaging="true" 
        TypeName="CustomerLogic" 
        SelectMethod="GetSubsetOfEmployees"
        MaximumRowsParameterName="maxRows"
        StartRowIndexParameterName="startRows"
        ID="ObjectDataSource1" 
        runat="server">
    </asp:ObjectDataSource>
    
    <asp:GridView 
        DataSourceID="ObjectDataSource1" 
        AllowPaging="true" 
        ID="GridView1" 
        runat="server">
    </asp:GridView>
    
    </div>
    </form>
</body>
</html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    How many rows to display on this page:<br />
    <asp:DropDownList 
          AutoPostBack="true" 
          ID="rowsToDisplay" 
          runat="server" 
          onselectedindexchanged="rowsToDisplay_SelectedIndexChanged">
        <asp:ListItem Value="5"></asp:ListItem>
        <asp:ListItem Value="10" Selected="True"></asp:ListItem>
        <asp:ListItem Value="20"></asp:ListItem>
    </asp:DropDownList> 
    
    <asp:ObjectDataSource 
        SelectCountMethod="GetEmployeeCount" 
        EnablePaging="true" 
        TypeName="CustomerLogic" 
        SelectMethod="GetSubsetOfEmployees"
        MaximumRowsParameterName="maxRows"
        StartRowIndexParameterName="startRows"
        ID="ObjectDataSource1" 
        runat="server">
    </asp:ObjectDataSource>
    
    <asp:GridView 
        DataSourceID="ObjectDataSource1" 
        AllowPaging="true" 
        ID="GridView1" 
        runat="server">
    </asp:GridView>
    
    </div>
    </form>
</body>
</html>

Во втором примере показан обработчик события ListControl.SelectedIndexChangedDropDownList элемента управления. Код в обработчике задает PageSize свойство для выбора пользователя.

protected void rowsToDisplay_SelectedIndexChanged(object sender, EventArgs e)
{
    GridView1.PageSize = int.Parse(rowsToDisplay.SelectedValue);
}
Protected Sub rowsToDisplay_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles rowsToDisplay.SelectedIndexChanged
    GridView1.PageSize = Integer.Parse(rowsToDisplay.SelectedValue)
End Sub

В третьем примере показан класс доступа к данным, извлекающий данные из таблицы Customers. Он включает метод с именем GetSubsetOfEmployees, который назначается SelectMethod свойству ObjectDataSource элемента управления. В примере также содержится метод с именем GetEmployeeCount, который назначается SelectCountMethod свойству ObjectDataSource элемента управления. Класс использует LINQ для запроса таблицы Customers. В этом примере требуется класс LINQ to SQL, представляющий базу данных Northwind и таблицу Customers. Дополнительные сведения см. в статье "Создание классов LINQ to SQL" в веб-проекте.

public class CustomerLogic
{

    public List<Customer> GetSubsetOfEmployees(int startRows, int maxRows)
    {
        NorthwindDataContext ndc = new NorthwindDataContext();
        var customerQuery = 
            from c in ndc.Customers
            select c;

        return customerQuery.Skip(startRows).Take(maxRows).ToList<Customer>();
    }

    public int GetEmployeeCount()
    {
        object cachedCount = HttpRuntime.Cache["TotalEmployeeCount"];
        if (cachedCount != null)
        {
            return int.Parse(cachedCount.ToString());
        }
        else
        {
            NorthwindDataContext ndc = new NorthwindDataContext();
            var totalNumberQuery =
                from c in ndc.Customers
                select c;
            
            int employeeCount = totalNumberQuery.Count();
            HttpRuntime.Cache.Add("TotalEmployeeCount", employeeCount, null, DateTime.Now.AddMinutes(5), Cache.NoSlidingExpiration, CacheItemPriority.Normal, null);
            return employeeCount;
        }
    }
}
Public Class CustomerLogic
    Public Function GetSubsetOfEmployees(ByVal startRows As Integer, ByVal maxRows As Integer) As List(Of Customer)

        Dim ndc As New NorthwindDataContext()
        Dim customerQuery = _
        From c In ndc.Customers _
            Select c

        Return customerQuery.Skip(startRows).Take(maxRows).ToList()
    End Function

    Public Function GetEmployeeCount() As Integer

        Dim cachedCount = HttpRuntime.Cache("TotalEmployeeCount")
        If cachedCount IsNot Nothing Then
            Return Integer.Parse(cachedCount.ToString())
        Else
            Dim ndc As New NorthwindDataContext()
            Dim totalNumberQuery = _
            From c In ndc.Customers _
                Select c

            Dim employeeCount = totalNumberQuery.Count()
            HttpRuntime.Cache.Add("TotalEmployeeCount", employeeCount, Nothing, DateTime.Now.AddMinutes(5), Cache.NoSlidingExpiration, CacheItemPriority.Normal, Nothing)
            Return employeeCount
        End If
    End Function
End Class

Комментарии

Свойство SelectCountMethod определяет метод бизнес-объекта, используемый для получения общего количества строк для поддержки разбиения по страницам источника данных. Свойство SelectCountMethod вычисляется только в том случае, если EnablePaging для свойства задано значение true.

Свойство SelectCountMethod делегирует SelectCountMethod свойству объекта, связанного ObjectDataSourceView с элементом ObjectDataSource управления. Сведения о том, как разбиение по страницам поддерживается элементом ObjectDataSource управления, см. в разделе EnablePaging.

Применяется к

См. также раздел