GridViewRowCollection Класс

Определение

Представляет коллекцию объектов GridViewRow в элементе управления GridView.

public ref class GridViewRowCollection : System::Collections::ICollection
public class GridViewRowCollection : System.Collections.ICollection
type GridViewRowCollection = class
    interface ICollection
    interface IEnumerable
Public Class GridViewRowCollection
Implements ICollection
Наследование
GridViewRowCollection
Реализации

Примеры

В следующем примере показано, как выполнить итерацию по Rows коллекции GridView элемента управления и отобразить значения столбца на странице.


<%@ Page language="C#" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">

  void AuthorsGridView_RowCreated(Object sender, GridViewRowEventArgs e)
  {
    if (e.Row.RowType == DataControlRowType.Footer)
    {      
      
      // Get the number of items in the Rows collection.
      int count = AuthorsGridView.Rows.Count;

      // If the GridView control contains any records, display 
      // the last name of each author in the GridView control.
      if (count > 0)
      {      
        Message.Text = "The authors are:<br />";
        
        foreach (GridViewRow row in AuthorsGridView.Rows)
        {
          Message.Text += row.Cells[0].Text + "<br />";
        }
      }
      
    }
  }

</script>

<html xmlns="http://www.w3.org/1999/xhtml" >
  <head runat="server">
    <title>GridViewRowCollection Example</title>
</head>
<body>
    <form id="form1" runat="server">
        
      <h3>GridViewRowCollection Example</h3>

      <table>
        <tr>
          <td>
            <asp:gridview id="AuthorsGridView" 
              datasourceid="AuthorsSqlDataSource" 
              autogeneratecolumns="false"
              onrowcreated="AuthorsGridView_RowCreated"  
              runat="server"> 
                     
              <columns>
                <asp:boundfield datafield="au_lname"
                  headertext="Last Name"/>
                <asp:boundfield datafield="au_fname"
                  headertext="First Name"/>
              </columns>
                                    
            </asp:gridview>
          </td>
          <td>
            <asp:label id="Message" 
              forecolor="Red"
              runat="server"/>
          </td>
        </tr>
      </table>
            
      <!-- This example uses Microsoft SQL Server and connects -->
      <!-- to the Pubs sample database.                        -->
      <asp:sqldatasource id="AuthorsSqlDataSource"  
        selectcommand="SELECT [au_lname], [au_fname] FROM [authors] WHERE [state]='CA'"
        connectionstring="server=localhost;database=pubs;integrated security=SSPI"
        runat="server">
      </asp:sqldatasource>
          
    </form>
  </body>
</html>

<%@ Page language="VB" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">

  Sub AuthorsGridView_RowCreated(ByVal sender As Object, ByVal e As GridViewRowEventArgs)

    If e.Row.RowType = DataControlRowType.Footer Then
      
      ' Get the number of items in the Rows collection.
      Dim count As Integer = AuthorsGridView.Rows.Count

      ' If the GridView control contains any records, display 
      ' the last name of each author in the GridView control.
      If count > 0 Then
           
        Message.Text = "The authors are:<br />"
        
        Dim row As GridViewRow
        For Each row In AuthorsGridView.Rows
        
          Message.Text &= row.Cells(0).Text & "<br />"
        
        Next
        
      End If
        
    End If
        
  End Sub

</script>

<html xmlns="http://www.w3.org/1999/xhtml" >
  <head runat="server">
    <title>GridViewRowCollection Example</title>
</head>
<body>
    <form id="form1" runat="server">
        
      <h3>GridViewRowCollection Example</h3>

      <table>
        <tr>
          <td>
            <asp:gridview id="AuthorsGridView" 
              datasourceid="AuthorsSqlDataSource" 
              autogeneratecolumns="false"
              onrowcreated="AuthorsGridView_RowCreated"  
              runat="server"> 
                     
              <columns>
                <asp:boundfield datafield="au_lname"
                  headertext="Last Name"/>
                <asp:boundfield datafield="au_fname"
                  headertext="First Name"/>
              </columns>
                                    
            </asp:gridview>
          </td>
          <td>
            <asp:label id="Message" 
              forecolor="Red"
              runat="server"/>
          </td>
        </tr>
      </table>
            
      <!-- This example uses Microsoft SQL Server and connects -->
      <!-- to the Pubs sample database.                        -->
      <asp:sqldatasource id="AuthorsSqlDataSource"  
        selectcommand="SELECT [au_lname], [au_fname] FROM [authors] WHERE [state]='CA'"
        connectionstring="server=localhost;database=pubs;integrated security=SSPI"
        runat="server">
      </asp:sqldatasource>
          
    </form>
  </body>
</html>

Комментарии

Класс GridViewRowCollection используется для хранения коллекции GridViewRow объектов в элементе управления и управления ими GridView . Каждая строка элемента GridView управления представлена GridViewRow объектом. Элемент GridView управления сохраняет все строки данных в Rows коллекции.

Класс GridViewRowCollection поддерживает несколько способов доступа к элементам в коллекции:

  • Item[] Используйте индексатор для непосредственного GridViewRow получения объекта по определенному отсчитываемого от нуля индексу.

  • GetEnumerator Используйте метод для получения перечислителя, который можно использовать для итерации по коллекции.

  • CopyTo Используйте метод для копирования элементов коллекции в System.Array объект, который затем можно использовать для доступа к элементам в коллекции.

Чтобы определить общее количество элементов в коллекции, используйте Count свойство

Конструкторы

GridViewRowCollection(ArrayList)

Инициализирует новый экземпляр класса GridViewRowCollection, используя указанный объект ArrayList.

Свойства

Count

Возвращает количество элементов в объекте GridViewRowCollection.

IsReadOnly

Возвращает значение, показывающее, могут ли изменяться строки в объекте GridViewRowCollection.

IsSynchronized

Возвращает значение, которое показывает, является ли объект GridViewRowCollection синхронизированным (потокобезопасным).

Item[Int32]

Возвращает объект GridViewRow по указанному индексу.

SyncRoot

Получает объект, используемый для синхронизации доступа к коллекции.

Методы

CopyTo(GridViewRow[], Int32)

Копирует все элементы из данного класса GridViewRowCollection в указанный объект Array, начиная с указанного индекса в объекте Array.

Equals(Object)

Определяет, равен ли указанный объект текущему объекту.

(Унаследовано от Object)
GetEnumerator()

Возвращает перечислитель, содержащий все объекты GridViewRow в коллекции GridViewRowCollection.

GetHashCode()

Служит хэш-функцией по умолчанию.

(Унаследовано от Object)
GetType()

Возвращает объект Type для текущего экземпляра.

(Унаследовано от Object)
MemberwiseClone()

Создает неполную копию текущего объекта Object.

(Унаследовано от Object)
ToString()

Возвращает строку, представляющую текущий объект.

(Унаследовано от Object)

Явные реализации интерфейса

ICollection.CopyTo(Array, Int32)

Описание этого члена см. в разделе CopyTo(Array, Int32).

Методы расширения

Cast<TResult>(IEnumerable)

Приводит элементы объекта IEnumerable к заданному типу.

OfType<TResult>(IEnumerable)

Выполняет фильтрацию элементов объекта IEnumerable по заданному типу.

AsParallel(IEnumerable)

Позволяет осуществлять параллельный запрос.

AsQueryable(IEnumerable)

Преобразовывает коллекцию IEnumerable в объект IQueryable.

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

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