DataGridColumnCollection Класс
Определение
Важно!
Некоторые сведения относятся к предварительной версии продукта, в которую до выпуска могут быть внесены существенные изменения. Майкрософт не предоставляет никаких гарантий, явных или подразумеваемых, относительно приведенных здесь сведений.
Коллекция производных объектов столбцов DataGridColumn, представляющих столбцы в элементе DataGrid управления. Этот класс не может быть унаследован.
public ref class DataGridColumnCollection sealed : System::Collections::ICollection, System::Web::UI::IStateManager
public sealed class DataGridColumnCollection : System.Collections.ICollection, System.Web.UI.IStateManager
type DataGridColumnCollection = class
interface ICollection
interface IEnumerable
interface IStateManager
Public NotInheritable Class DataGridColumnCollection
Implements ICollection, IStateManager
- Наследование
-
DataGridColumnCollection
- Реализации
Примеры
В следующем примере кода показано, как использовать DataGridColumnCollection коллекцию для динамического добавления столбца в DataGrid элемент управления. Обратите внимание, что Columns свойство DataGrid элемента управления является экземпляром DataGridColumnCollection класса.
<%@ Page Language="C#" AutoEventWireup="True" %>
<%@ Import Namespace="System.Data" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<script runat="server">
ICollection CreateDataSource()
{
// Create sample data for the DataGrid control.
DataTable dt = new DataTable();
DataRow dr;
// Define the columns of the table.
dt.Columns.Add(new DataColumn("IntegerValue", typeof(Int32)));
dt.Columns.Add(new DataColumn("StringValue", typeof(string)));
dt.Columns.Add(new DataColumn("CurrencyValue", typeof(double)));
// Populate the table with sample values.
for (int i = 0; i < 9; i++)
{
dr = dt.NewRow();
dr[0] = i;
dr[1] = "Item " + i.ToString();
dr[2] = 1.23 * (i + 1);
dt.Rows.Add(dr);
}
DataView dv = new DataView(dt);
return dv;
}
void Page_Load(Object sender, EventArgs e)
{
// Create a DataGrid control.
DataGrid ItemsGrid = new DataGrid();
// Set the properties of the DataGrid.
ItemsGrid.ID = "ItemsGrid";
ItemsGrid.BorderColor = System.Drawing.Color.Black;
ItemsGrid.CellPadding = 3;
ItemsGrid.AutoGenerateColumns = false;
// Set the styles for the DataGrid.
ItemsGrid.HeaderStyle.BackColor =
System.Drawing.Color.FromArgb(0x0000aaaa);
// Create the columns for the DataGrid control. The DataGrid
// columns are dynamically generated. Therefore, the columns
// must be re-created each time the page is refreshed.
// Create and add the columns to the collection.
ItemsGrid.Columns.Add(CreateBoundColumn("IntegerValue", "Item"));
ItemsGrid.Columns.Add(
CreateBoundColumn("StringValue", "Description"));
ItemsGrid.Columns.Add(
CreateBoundColumn("CurrencyValue", "Price", "{0:c}",
HorizontalAlign.Right));
ItemsGrid.Columns.Add(
CreateLinkColumn("http://www.microsoft.com", "_self",
"Microsoft", "Related link"));
// Specify the data source and bind it to the control.
ItemsGrid.DataSource = CreateDataSource();
ItemsGrid.DataBind();
// Add the DataGrid control to the Controls collection of
// the PlaceHolder control.
Place.Controls.Add(ItemsGrid);
}
BoundColumn CreateBoundColumn(String DataFieldValue,
String HeaderTextValue)
{
// This version of the CreateBoundColumn method sets only the
// DataField and HeaderText properties.
// Create a BoundColumn.
BoundColumn column = new BoundColumn();
// Set the properties of the BoundColumn.
column.DataField = DataFieldValue;
column.HeaderText = HeaderTextValue;
return column;
}
BoundColumn CreateBoundColumn(String DataFieldValue,
String HeaderTextValue, String FormatValue,
HorizontalAlign AlignValue)
{
// This version of CreateBoundColumn method sets the DataField,
// HeaderText, and DataFormatString properties. It also sets the
// HorizontalAlign property of the ItemStyle property of the column.
// Create a BoundColumn using the overloaded CreateBoundColumn method.
BoundColumn column = CreateBoundColumn(DataFieldValue, HeaderTextValue);
// Set the properties of the BoundColumn.
column.DataFormatString = FormatValue;
column.ItemStyle.HorizontalAlign = AlignValue;
return column;
}
HyperLinkColumn CreateLinkColumn(String NavUrlValue,
String TargetValue, String TextValue, String HeaderTextValue)
{
// Create a BoundColumn.
HyperLinkColumn column = new HyperLinkColumn();
// Set the properties of the ButtonColumn.
column.NavigateUrl = NavUrlValue;
column.Target = TargetValue;
column.Text = TextValue;
column.HeaderText = HeaderTextValue;
return column;
}
</script>
<head runat="server">
<title>DataGrid Constructor Example</title>
</head>
<body>
<form id="form1" runat="server">
<h3>DataGrid Constructor Example</h3>
<b>Product List</b>
<asp:PlaceHolder id="Place"
runat="server"/>
</form>
</body>
</html>
<%@ Page Language="VB" AutoEventWireup="True" %>
<%@ Import Namespace="System.Data" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<script runat="server">
Function CreateDataSource() As ICollection
' Create sample data for the DataGrid control.
Dim dt As DataTable = New DataTable()
Dim dr As DataRow
' Define the columns of the table.
dt.Columns.Add(New DataColumn("IntegerValue", GetType(Int32)))
dt.Columns.Add(New DataColumn("StringValue", GetType(string)))
dt.Columns.Add(New DataColumn("CurrencyValue", GetType(double)))
' Populate the table with sample values.
Dim i As Integer
For i = 0 to 8
dr = dt.NewRow()
dr(0) = i
dr(1) = "Item " & i.ToString()
dr(2) = 1.23 * (i + 1)
dt.Rows.Add(dr)
Next i
Dim dv As DataView = New DataView(dt)
Return dv
End Function
Sub Page_Load(sender As Object, e As EventArgs)
' Create a DataGrid control.
Dim ItemsGrid As DataGrid = New DataGrid()
' Set the properties of the DataGrid.
ItemsGrid.ID = "ItemsGrid"
ItemsGrid.BorderColor = System.Drawing.Color.Black
ItemsGrid.CellPadding = 3
ItemsGrid.AutoGenerateColumns = False
' Set the styles for the DataGrid.
ItemsGrid.HeaderStyle.BackColor = System.Drawing.Color.FromArgb(&H0000aaaa)
' Create the columns for the DataGrid control. The DataGrid
' columns are dynamically generated. Therefore, the columns
' must be re-created each time the page is refreshed.
' Create and add the columns to the collection.
ItemsGrid.Columns.Add(CreateBoundColumn("IntegerValue", "Item"))
ItemsGrid.Columns.Add( _
CreateBoundColumn("StringValue", "Description"))
ItemsGrid.Columns.Add( _
CreateBoundColumn("CurrencyValue", "Price", "{0:c}", _
HorizontalAlign.Right))
ItemsGrid.Columns.Add( _
CreateLinkColumn("http:'www.microsoft.com", "_self", _
"Microsoft", "Related link"))
' Specify the data source and bind it to the control.
ItemsGrid.DataSource = CreateDataSource()
ItemsGrid.DataBind()
' Add the DataGrid control to the Controls collection of
' the PlaceHolder control.
Place.Controls.Add(ItemsGrid)
End Sub
Function CreateBoundColumn(DataFieldValue As String, HeaderTextValue As String) As BoundColumn
' This version of CreateBoundColumn method sets only the
' DataField and HeaderText properties.
' Create a BoundColumn.
Dim column As BoundColumn = New BoundColumn()
' Set the properties of the BoundColumn.
column.DataField = DataFieldValue
column.HeaderText = HeaderTextValue
Return column
End Function
Function CreateBoundColumn(DataFieldValue As String, _
HeaderTextValue As String, FormatValue As String, _
AlignValue As HorizontalAlign) As BoundColumn
' This version of CreateBoundColumn method sets the DataField,
' HeaderText, and DataFormatString properties. It also sets the
' HorizontalAlign property of the ItemStyle property of the column.
' Create a BoundColumn using the overloaded CreateBoundColumn method.
Dim column As BoundColumn = CreateBoundColumn(DataFieldValue, HeaderTextValue)
' Set the properties of the BoundColumn.
column.DataFormatString = FormatValue
column.ItemStyle.HorizontalAlign = AlignValue
Return column
End Function
Function CreateLinkColumn(NavUrlValue As String, TargetValue As String, _
TextValue As String, HeaderTextValue As String) As HyperLinkColumn
' Create a BoundColumn.
Dim column As HyperLinkColumn = New HyperLinkColumn()
' Set the properties of the ButtonColumn.
column.NavigateUrl = NavUrlValue
column.Target = TargetValue
column.Text = TextValue
column.HeaderText = HeaderTextValue
Return column
End Function
</script>
<head runat="server">
<title>DataGrid Constructor Example</title>
</head>
<body>
<form id="form1" runat="server">
<h3>DataGrid Constructor Example</h3>
<b>Product List</b>
<asp:PlaceHolder id="Place"
runat="server"/>
</form>
</body>
</html>
Комментарии
Используйте коллекцию DataGridColumnCollection для программного управления коллекцией объектов производных столбцов DataGridColumn. Эти объекты представляют столбцы в элементе DataGrid управления. Вы можете добавлять, удалять или вставлять столбцы в коллекцию DataGridColumnCollection .
Замечание
AutoGenerateColumns Если для свойства заданы true, столбцы, созданные элементом управления, DataGrid не добавляются в коллекциюColumns.
Элемент DataGrid управления не сохраняет содержимое коллекции Columns в состоянии представления. Чтобы добавить или удалить столбец динамически, необходимо программно добавлять или удалять столбец при каждом обновлении страницы.
Page_Init Предоставьте функцию, которая добавляет или удаляет столбец перед DataGrid перезагрузкой состояния элемента управления и перестроен элемент управления. В противном случае изменения Columns коллекции не отражаются в DataGrid элементе управления при отображении.
Замечание
Хотя вы можете программным способом добавлять столбцы в коллекцию элементов управления или удалять их из Columns коллекции DataGrid , проще перечислять столбцы статически, а затем использовать Visible свойство для отображения или скрытия каждого столбца.
Порядок столбцов в коллекции определяет порядок отображения столбцов в элементе DataGrid управления.
В следующей таблице перечислены различные классы столбцов, производные от DataGridColumn класса.
| Класс столбцов | Описание |
|---|---|
| BoundColumn | Столбец, привязанный к полю в источнике данных. Он отображает каждый элемент в поле в виде текста. Это тип столбца DataGrid по умолчанию для элемента управления. |
| ButtonColumn | Столбец, отображающий кнопку команды для каждого элемента в столбце. Это позволяет создать столбец пользовательских элементов управления кнопками, например кнопки "Добавить" или "Удалить". |
| EditCommandColumn | Столбец, содержащий команды редактирования для каждого элемента в столбце. |
| HyperLinkColumn | Столбец, отображающий каждый элемент в столбце в виде гиперссылки. Содержимое столбца может быть привязано к полю в источнике данных или к статическому тексту. |
| TemplateColumn | Столбец, отображающий каждый элемент в столбце в соответствии с указанным шаблоном. Это позволяет управлять содержимым столбца, например отображать изображения. |
Замечание
Класс DataGridColumn является базовым классом для перечисленных классов столбцов. Он не используется непосредственно в DataGridColumnCollection коллекции.
Конструкторы
| Имя | Описание |
|---|---|
| DataGridColumnCollection(DataGrid, ArrayList) |
Инициализирует новый экземпляр класса DataGridColumnCollection. |
Свойства
| Имя | Описание |
|---|---|
| Count |
Возвращает количество столбцов в DataGridColumnCollection коллекции. |
| IsReadOnly |
Возвращает значение, указывающее, можно ли изменять столбцы в DataGridColumnCollection коллекции. |
| IsSynchronized |
Возвращает значение, указывающее, синхронизирован ли доступ к DataGridColumnCollection коллекции (потокобезопасный). |
| Item[Int32] |
Получает производный DataGridColumnот коллекции объект столбца по DataGridColumnCollection указанному индексу. |
| SyncRoot |
Возвращает объект, который можно использовать для синхронизации доступа к DataGridColumnCollection коллекции. |
Методы
| Имя | Описание |
|---|---|
| Add(DataGridColumn) |
Добавляет указанный DataGridColumnобъект производного DataGridColumnCollection столбца к концу коллекции. |
| AddAt(Int32, DataGridColumn) |
Вставляет объект-производный DataGridColumnстолбец в DataGridColumnCollection коллекцию по указанному индексу. |
| Clear() |
Удаляет все DataGridColumnпроизводные DataGridColumnCollection объекты столбцов из коллекции. |
| CopyTo(Array, Int32) |
Копирует элементы из DataGridColumnCollection коллекции в указанный Array, начиная с указанного индекса в объекте Array. |
| Equals(Object) |
Определяет, равен ли указанный объект текущему объекту. (Унаследовано от Object) |
| GetEnumerator() |
IEnumerator Возвращает интерфейс, содержащий все объекты производных DataGridColumnстолбцов в DataGridColumnCollection коллекции. |
| GetHashCode() |
Служит хэш-функцией по умолчанию. (Унаследовано от Object) |
| GetType() |
Возвращает Type текущего экземпляра. (Унаследовано от Object) |
| IndexOf(DataGridColumn) |
Возвращает индекс указанного DataGridColumnобъекта столбца, производного от DataGridColumnCollection коллекции. |
| MemberwiseClone() |
Создает неглубокую копию текущей Object. (Унаследовано от Object) |
| Remove(DataGridColumn) |
Удаляет указанный DataGridColumnобъект столбца, производный от имени, из DataGridColumnCollection коллекции. |
| RemoveAt(Int32) |
Удаляет объект производного DataGridColumnстолбца из DataGridColumnCollection коллекции по указанному индексу. |
| ToString() |
Возвращает строку, представляющую текущий объект. (Унаследовано от Object) |
Явные реализации интерфейса
| Имя | Описание |
|---|---|
| IStateManager.IsTrackingViewState |
Возвращает значение, указывающее, отслеживает ли коллекция изменения состояния представления. |
| IStateManager.LoadViewState(Object) |
Загружает ранее сохраненное состояние. |
| IStateManager.SaveViewState() |
Возвращает объект, содержащий изменения состояния. |
| IStateManager.TrackViewState() |
Запускает отслеживание изменений состояния. |
Методы расширения
| Имя | Описание |
|---|---|
| AsParallel(IEnumerable) |
Включает параллелизацию запроса. |
| AsQueryable(IEnumerable) |
Преобразует IEnumerable в IQueryable. |
| Cast<TResult>(IEnumerable) |
Приведение элементов IEnumerable к указанному типу. |
| OfType<TResult>(IEnumerable) |
Фильтрует элементы IEnumerable на основе указанного типа. |