The windows forms datagridview

Data Grid View Row Класс

Определение

Представляет строку в элементе управления DataGridView. Represents a row in a DataGridView control.

Примеры

В следующем примере кода показано использование этого типа. The following code example illustrates the use of this type. Этот пример является частью более крупного примера, в котором показано, как управлять строками в элементе управления Windows Forms DataGridView. This example is part of a larger example available in How to: Manipulate Rows in the Windows Forms DataGridView Control.

Комментарии

DataGridViewRowКласс представляет строку в DataGridView элементе управления. The DataGridViewRow class represents a row in a DataGridView control. Строки можно получить с помощью Rows коллекций и SelectedRows элемента управления. You can retrieve rows through the Rows and SelectedRows collections of the control.

В отличие от DataGridViewColumn , DataGridViewRow физически содержит коллекцию всех ячеек в этой строке. Unlike a DataGridViewColumn, a DataGridViewRow physically contains a collection of all of the cells in that row. Доступ к этой коллекции можно получить с помощью Cells Свойства. You can access this collection through the Cells property.

DataGridViewRowКласс используется для доступа к отдельным элементам ячейки, а также для настройки внешнего вида и поведения пользовательского интерфейса строки, например высоты и стиля ячейки. The DataGridViewRow class is used to access the individual cell elements, as well as to adjust the appearance and behavior of the row user interface (UI), such as height and cell style. Как правило, все строки или большинство строк в элементе управления должны иметь одинаковые характеристики. Typically, you will want all rows or most rows in the control to share the same characteristics. Чтобы задать стили ячеек для всех строк в элементе управления, задайте свойства объекта, возвращаемого DataGridView.RowsDefaultCellStyle свойством. To set cell styles for all rows in the control, set the properties of the object returned by the DataGridView.RowsDefaultCellStyle property. Чтобы задать стили для чередующихся строк, используйте DataGridView.AlternatingRowsDefaultCellStyle свойство. To set styles for alternating rows, use the DataGridView.AlternatingRowsDefaultCellStyle property. Дополнительные сведения о стилях ячеек см. в разделе Стили ячеек в элементе управления Windows Forms DataGridView. For more information about cell styles, see Cell Styles in the Windows Forms DataGridView Control. Можно также использовать DataGridView.RowTemplate свойство для определения строки, которая будет использоваться в качестве базиса для всех строк, добавляемых в элемент управления. You can also use the DataGridView.RowTemplate property to define a row that will be used as a basis for all rows added to the control.

DataGridViewЭлемент управления будет совместно использовать DataGridViewRow объекты в нескольких строках данных, если это возможно, чтобы избежать снижения производительности. The DataGridView control will share DataGridViewRow objects across multiple data rows whenever possible to avoid performance penalties. Если вы не работаете с большими объемами данных и испытываете проблемы с производительностью, обычно можно пропустить общий доступ к строкам. Unless you are working with large amounts of data and experiencing performance issues, you can typically ignore row sharing. Общая строка обозначается Index значением свойства-1. A shared row is indicated by an Index property value of -1. Некоторые члены DataGridViewRow класса не могут использоваться с общими строками, но можно отменить общий доступ к строке с помощью DataGridViewRowCollection.Item[] Свойства. Some members of the DataGridViewRow class cannot be used with shared rows, but you can unshare a row by accessing it through the DataGridViewRowCollection.Item[] property. Строки также могут быть отличных от общего доступа другими способами. Rows can also become unshared in other ways. Чтобы получить доступ к строке, не отменяя общий доступ к ней, используйте DataGridViewRowCollection.SharedRow метод. To access a row without unsharing it, use the DataGridViewRowCollection.SharedRow method. При работе с большими объемами данных следует иметь в виду, как совместно используются и отменяются совместное использование строк во избежание снижения производительности. When working with large amounts of data, you should be aware of how rows are shared and unshared to avoid performance penalties. Подробнее см. в разделе Масштабирование элемента управления DataGridView в Windows Forms. For more information, see Best Practices for Scaling the Windows Forms DataGridView Control.

Примечания для тех, кто наследует этот метод

При наследовании от DataGridViewRow и добавлении новых свойств в производный класс обязательно Переопределите Clone() метод, чтобы скопировать новые свойства во время операций клонирования. When you derive from DataGridViewRow and add new properties to the derived class, be sure to override the Clone() method to copy the new properties during cloning operations. Также следует вызвать метод базового класса, Clone() чтобы свойства базового класса копировались в новую ячейку. You should also call the base class’s Clone() method so that the properties of the base class are copied to the new cell.

Читайте также:  Поиск mail ru для windows

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

Инициализирует новый экземпляр класса DataGridViewRow без использования шаблона. Initializes a new instance of the DataGridViewRow class without using a template.

Свойства

Возвращает коллекцию ячеек, заполняющих строку. Gets the collection of cells that populate the row.

Возвращает или задает контекстное меню для строки. Gets or sets the shortcut menu for the row.

Возвращает связанный с данными объект, наполнивший строку. Gets the data-bound object that populated the row.

Получает элемент управления DataGridView, связанный с данным элементом. Gets the DataGridView control associated with this element.

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

Возвращает или задает стили по умолчанию для строки, которые используются для визуализации ячеек в строке, если стили не переопределены. Gets or sets the default styles for the row, which are used to render cells in the row unless the styles are overridden.

Получает или задает тип времени выполнения для ячейки заголовка по умолчанию. Gets or sets the run-time type of the default header cell.

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

Возвращает значение, указывающее, отображается ли данная строка на экране. Gets a value indicating whether this row is displayed on the screen.

Возвращает или задает высоту разделителя строки в пикселях. Gets or sets the height, in pixels, of the row divider.

Возвращает или задает текст сообщения об ошибке для ошибок уровня строки. Gets or sets the error message text for row-level errors.

Возвращает или задает значение, показывающее, является ли строка замороженной. Gets or sets a value indicating whether the row is frozen.

Получает значение, показывающее, было ли установлено свойство DefaultCellStyle. Gets a value indicating whether the DefaultCellStyle property has been set.

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

Возвращает или задает ячейку заголовка строки. Gets or sets the row’s header cell.

Получает или задает ячейку заголовка объекта DataGridViewBand. Gets or sets the header cell of the DataGridViewBand.

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

Возвращает или задает текущую высоту строки. Gets or sets the current height of the row.

Получает относительную позицию диапазона в элементе управления DataGridView. Gets the relative position of the band within the DataGridView control.

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

Возвращает стиль ячейки, применяемый для данной строки. Gets the cell style in effect for the row.

Возвращает значение, указывающее, является ли строка строкой для новых записей. Gets a value indicating whether the row is the row for new records.

Получает значение, показывающее, представляет ли диапазон строку. Gets a value indicating whether the band represents a row.

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

Возвращает или задает минимальную высоту строки. Gets or sets the minimum height of the row.

Возвращает или задает значение, указывающее, является ли строка доступной только для чтения. Gets or sets a value indicating whether the row is read-only.

Возвращает или задает значение, указывающее, могут ли пользователи изменять размер строки. Также может указывать, унаследовано ли поведение от AllowUserToResizeRows. Gets or sets a value indicating whether users can resize the row or indicating that the behavior is inherited from the AllowUserToResizeRows property.

Получает или задает значение, указывающее, выбрана ли строка. Gets or sets a value indicating whether the row is selected.

Возвращает текущее состояние строки. Gets the current state of the row.

Получает или задает объект, содержащий данные, связанные с диапазоном. Gets or sets the object that contains data to associate with the band.

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

Возвращает или задает значение, показывающее, является ли строка видимой. Gets or sets a value indicating whether the row is visible.

Методы

Изменяет стиль границы заголовка входной строки в соответствии с указанными критериями. Modifies an input row header border style according to the specified criteria.

Создает точную копию данной строки. Creates an exact copy of this row.

Создает новый доступный объект для DataGridViewRow. Creates a new accessible object for the DataGridViewRow.

Очищает существующие ячейки и задает их шаблон в соответствии с предоставленным шаблоном DataGridView. Clears the existing cells and sets their template according to the supplied DataGridView template.

Очищает существующие ячейки и задает их шаблон и значения. Clears the existing cells and sets their template and values.

Создает новую коллекцию ячеек на основе данной строки. Constructs a new collection of cells based on this row.

Освобождает все ресурсы, занятые модулем DataGridViewBand. Releases all resources used by the DataGridViewBand.

(Унаследовано от DataGridViewBand) Dispose(Boolean)

Освобождает неуправляемые ресурсы, используемые объектом DataGridViewBand, а при необходимости освобождает также управляемые ресурсы. Releases the unmanaged resources used by the DataGridViewBand and optionally releases the managed resources.

(Унаследовано от DataGridViewBand) DrawFocus(Graphics, Rectangle, Rectangle, Int32, DataGridViewElementStates, DataGridViewCellStyle, Boolean)

Отрисовывает прямоугольник фокуса вокруг указанных границ. Draws a focus rectangle around the specified bounds.

Определяет, равен ли указанный объект текущему объекту. Determines whether the specified object is equal to the current object.

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

Возвращает контекстное меню для строки. Gets the shortcut menu for the row.

Читайте также:  Mpc hc ��� linux

Возвращает текст ошибки для строки, находящейся по указанному индексу. Gets the error text for the row at the specified index.

Служит хэш-функцией по умолчанию. Serves as the default hash function.

(Унаследовано от Object) GetPreferredHeight(Int32, DataGridViewAutoSizeRowMode, Boolean)

Вычисляет идеальную высоту указанной строки, исходя из заданных критериев. Calculates the ideal height of the specified row based on the specified criteria.

Возвращает значение, указывающее текущее состояние строки. Returns a value indicating the current state of the row.

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

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

Создает неполную копию текущего объекта Object. Creates a shallow copy of the current Object.

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

Вызывается, когда диапазон связан с другим элементом управления DataGridView. Called when the band is associated with a different DataGridView.

(Унаследовано от DataGridViewBand) Paint(Graphics, Rectangle, Rectangle, Int32, DataGridViewElementStates, Boolean, Boolean)

Закрашивает текущую строку. Paints the current row.

Закрашивает ячейки в текущей строке. Paints the cells in the current row.

Закрашивает ячейку заголовка текущей строки. Paints the header cell of the current row.

Вызывает событие CellClick. Raises the CellClick event.

(Унаследовано от DataGridViewElement) RaiseCellContentClick(DataGridViewCellEventArgs)

Вызывает событие CellContentClick. Raises the CellContentClick event.

(Унаследовано от DataGridViewElement) RaiseCellContentDoubleClick(DataGridViewCellEventArgs)

(Унаследовано от DataGridViewElement) RaiseCellValueChanged(DataGridViewCellEventArgs)

Вызывает событие CellValueChanged. Raises the CellValueChanged event.

(Унаследовано от DataGridViewElement) RaiseDataError(DataGridViewDataErrorEventArgs)

Вызывает событие DataError. Raises the DataError event.

(Унаследовано от DataGridViewElement) RaiseMouseWheel(MouseEventArgs)

Вызывает событие MouseWheel. Raises the MouseWheel event.

(Унаследовано от DataGridViewElement) SetValues(Object[])

Задает значения ячеек строки. Sets the values of the row’s cells.

Возвращает понятно составленный текст, описывающий строку. Gets a human-readable string that describes the row.

Установка режимов заполнения для столбцов элемента управления DataGridView в Windows Forms Column Fill Mode in the Windows Forms DataGridView Control

В режиме заполнения столбцов элемент управления DataGridView автоматически изменяет размер своих столбцов, чтобы они полностью заполняли доступную область отображения по ширине. In column fill mode, the DataGridView control resizes its columns automatically so that they fill the width of the available display area. Элемент управления не отображает горизонтальную полосу прокрутки, за исключением случаев, когда необходимо сохранить ширину каждого столбца равной или большей, чем значение его свойства MinimumWidth. The control does not display the horizontal scroll bar except when it is necessary to keep the width of every column equal to or greater than its MinimumWidth property value.

Поведение каждого столбца при изменении размера зависит от его свойства InheritedAutoSizeMode. The sizing behavior of each column depends on its InheritedAutoSizeMode property. Значение этого свойства наследуется от свойства AutoSizeMode или свойства элемента управления AutoSizeColumnsMode, если значение столбца равно NotSet (значение по умолчанию). The value of this property is inherited from the column’s AutoSizeMode property or the control’s AutoSizeColumnsMode property if the column value is NotSet (the default value).

Каждый столбец может иметь свой режим определения размера, но все столбцы с режимом определения размера Fill будут совместно использовать ту ширину области отображения, которая не занята другими столбцами. Each column can have a different size mode, but any columns with a size mode of Fill will share the display-area width that is not used by the other columns. Эта ширина распределяется между столбцами с заполнением пропорционально значениям их свойств FillWeight. This width is divided among the fill-mode columns in proportions relative to their FillWeight property values. Например, если два столбца имеют значения FillWeight, равные 100 и 200, то первый столбец будет иметь половину от ширины второго столбца. For example, if two columns have FillWeight values of 100 and 200, the first column will be half as wide as the second column.

Изменение размера пользователем в режиме заполнения User Resizing in Fill Mode

В отличие от режимов определения размера на основе содержимого ячейки, режим заполнения запрещает пользователям изменение размеров столбцов, имеющих значения свойстваResizable, равные true . Unlike sizing modes that resize based on cell contents, fill mode does not prevent users from resizing columns that have Resizable property values of true . При изменении пользователем размера столбца в режиме заполнения все столбцы с заполнением после столбца с измененным размером (справа от него, если RightToLeft равно false , в противном случае — слева) также меняются, чтобы компенсировать изменение на доступную ширину. When a user resizes a fill-mode column, any fill-mode columns after the resized column (to the right if RightToLeft is false ; otherwise, to the left) are also resized to compensate for the change in the available width. Если после столбца с измененным размером нет столбцов с заполнением, то размеры всех остальных столбцов с заполнением в элементе управления изменяются для компенсации. If there are no fill-mode columns after the resized column, then all other fill-mode columns in the control are resized to compensate. Если в элементе управления нет других столбцов с заполнением, то изменение размера игнорируется. If there are no other fill-mode columns in the control, the resize is ignored. Если изменяется размер столбца, который не находится в режиме заполнения, то размеры всех столбцов с заполнением в элементе управления изменяются для компенсации. If a column that is not in fill mode is resized, all fill-mode columns in the control change sizes to compensate.

Читайте также:  Средства windows для работы с жестким диском

После изменения размера столбца с заполнением значения FillWeight для всех измененных столбцов будут пропорционально скорректированы. After resizing a fill-mode column, the FillWeight values for all columns that changed are adjusted proportionally. Например, если четыре столбца с заполнением имеют значения FillWeight, равные 100, то уменьшение ширины второго столбца в два раза приведет к изменению значений FillWeight в 100, 50, 125 и 125. For example, if four fill-mode columns have FillWeight values of 100, resizing the second column to half its original width will result in FillWeight values of 100, 50, 125, and 125. Изменение размера столбца без заполнения не приведет к изменению значения FillWeight, поскольку столбцы с заполнением просто компенсируют изменения, чтобы сохранить соотношения. Resizing a column that is not in fill mode will not change any FillWeight values because the fill-mode columns will simply resize to compensate while retaining the same proportions.

Коррекция на основе содержимого FillWeight Content-Based FillWeight Adjustment

Для столбцов с заполнением можно инициализировать значения FillWeight, используя методы автоматического изменения размера DataGridView, такие как метод AutoResizeColumns. You can initialize FillWeight values for fill-mode columns by using the DataGridView automatic resizing methods, such as the AutoResizeColumns method. Этот метод сначала вычисляет ширину столбцов, необходимую для отображения их содержимого. This method first calculates the widths required by columns to display their contents. Затем элемент управления корректирует значения FillWeight для всех столбцов с заполнением, чтобы их соотношение соответствовало соотношению рассчитанных значений ширины. Next, the control adjusts the FillWeight values for all fill-mode columns so that their proportions match the proportions of the calculated widths. И наконец, элемент управления изменяет размеры столбцов с заполнением с использованием нового соотношения FillWeight, таким образом, чтобы все столбцы в элементе управления заполняли доступное пространство по горизонтали. Finally, the control resizes the fill-mode columns using the new FillWeight proportions so that all columns in the control fill the available horizontal space.

Пример Example

Описание Description

Поведение размеров столбцов для различных сценариев можно настроить, используя соответствующие значения для свойств AutoSizeMode, MinimumWidth, FillWeight и Resizable. By using appropriate values for the AutoSizeMode, MinimumWidth, FillWeight, and Resizable properties, you can customize the column-sizing behaviors for many different scenarios.

В следующем примере кода можно поэкспериментировать с различными значениями для свойств AutoSizeMode, FillWeight и MinimumWidth различных столбцов. The following demonstration code enables you to experiment with different values for the AutoSizeMode, FillWeight, and MinimumWidth properties of different columns. В этом примере элемент управления DataGridView привязан к собственной коллекции Columns, а один столбец связан с каждым из свойств HeaderText, AutoSizeMode, FillWeight, MinimumWidth и Width. In this example, a DataGridView control is bound to its own Columns collection, and one column is bound to each of the HeaderText, AutoSizeMode, FillWeight, MinimumWidth, and Width properties. Каждый из столбцов также представлен строкой в элементе управления, и изменение значений в строке приведет к обновлению свойства соответствующего столбца, чтобы можно было увидеть взаимодействие значений. Each of the columns is also represented by a row in the control, and changing values in a row will update the properties of the corresponding column so that you can see how the values interact.

Код Code

Комментарии Comments

Использование этого демонстрационного приложения. To use this demonstration application:

Измените размер формы. Change the size of the form. Обратите внимание, как изменяется ширина столбцов и одновременно сохраняются пропорции, указанные значениями свойства FillWeight. Observe how columns change their widths while retaining the proportions indicated by the FillWeight property values.

Измените размеры столбцов, перетаскивая их разделители с помощью мыши. Change the column sizes by dragging the column dividers with the mouse. Обратите внимание, как изменяются значения FillWeight. Observe how the FillWeight values change.

Измените значение MinimumWidth для одного столбца, а затем перетащите для изменения размеров формы. Change the MinimumWidth value for one column, then drag to resize the form. Обратите внимание, что при достаточном уменьшении размера формы, значения Width не становятся меньше значений MinimumWidth. Observe how, when you make the form small enough, the Width values do not go below the MinimumWidth values.

Измените значения MinimumWidth для всех столбцов на большие числа, чтобы суммарное значение было больше ширины элемента управления. Change the MinimumWidth values for all columns to large numbers so that the combined values exceed the width of the control. Обратите внимание, как появляется горизонтальная полоса прокрутки. Observe how the horizontal scroll bar appears.

Измените значения AutoSizeMode для некоторых столбцов. Change the AutoSizeMode values for some columns. Наблюдайте результат при изменении размера столбцов или формы. Observe the effect when you resize columns or the form.

Компиляция кода Compiling the Code

Для этого примера требуются: This example requires:

Оцените статью