- Практическое руководство. Добавление таблиц и столбцов в элемент управления DataGrid в Windows Forms How to: Add Tables and Columns to the Windows Forms DataGrid Control
- Добавление таблицы и столбца в DataGrid программным способом To add a table and column to a DataGrid programmatically
- Создание таблиц подстановки в приложениях Windows Forms Create lookup tables in Windows Forms applications
- Привязка элемента управления «Уточняющий запрос» To databind a lookup control
- Создание таблицы
- Практическое руководство. Создание таблицы подстановок с помощью компонента BindingSource в формах Windows Forms How to: Create a Lookup Table with the Windows Forms BindingSource Component
- Создание пользовательского интерфейса To create the user interface
- Подключение к данным и их привязка к элементам управления To connect to the data and bind it to controls
Практическое руководство. Добавление таблиц и столбцов в элемент управления DataGrid в Windows Forms How to: Add Tables and Columns to the Windows Forms DataGrid Control
Элемент управления DataGridView заменяет элемент управления DataGrid и расширяет его функциональные возможности; однако при необходимости элемент управления DataGrid можно сохранить для обратной совместимости и использования в будущем. The DataGridView control replaces and adds functionality to the DataGrid control; however, the DataGrid control is retained for both backward compatibility and future use, if you choose. Дополнительные сведения см. в разделе Различия элементов управления DataGridView и DataGrid в Windows Forms. For more information, see Differences Between the Windows Forms DataGridView and DataGrid Controls.
Данные можно отображать в DataGrid элементах управления Windows Forms в таблицах и столбцах, создавая объекты DataGridTableStyle и добавляя их к объекту GridTableStylesCollection , доступ к которому осуществляется через DataGrid свойство TableStyles элемента управления. You can display data in the Windows Forms DataGrid control in tables and columns by creating DataGridTableStyle objects and adding them to the GridTableStylesCollection object, which is accessed through the DataGrid control’s TableStyles property. Каждый стиль таблицы отображает содержимое любой таблицы данных, указанной в свойстве MappingName объекта DataGridTableStyle . Each table style displays the contents of whatever data table is specified in the DataGridTableStyle object’s MappingName property. По умолчанию в стиле таблицы, в котором не указаны стили столбцов, отображаются все столбцы в таблице данных. By default, a table style with no column styles specified will display all the columns within that data table. Можно ограничить список отображаемых столбцов таблицы, добавив объекты DataGridColumnStyle в объект GridColumnStylesCollection , доступ к которому осуществляется через свойство GridColumnStyles каждого объекта DataGridTableStyle . You can restrict which columns from the table appear by adding DataGridColumnStyle objects to the GridColumnStylesCollection object, which is accessed through the GridColumnStyles property of each DataGridTableStyle object.
Добавление таблицы и столбца в DataGrid программным способом To add a table and column to a DataGrid programmatically
Чтобы отобразить данные в таблице, необходимо сначала привязать DataGrid элемент управления к набору данных. In order to display data in the table, you must first bind the DataGrid control to a dataset. Дополнительные сведения см. в разделе руководство. привязка Windows Forms элемента управления DataGrid к источнику данных. For more information, see How to: Bind the Windows Forms DataGrid Control to a Data Source.
При программном указании стилей столбцов всегда создавайте объекты DataGridColumnStyle и добавляйте их в объект GridColumnStylesCollection перед добавлением объектов DataGridTableStyle в объект GridTableStylesCollection . When programmatically specifying column styles, always create DataGridColumnStyle objects and add them to the GridColumnStylesCollection object before adding DataGridTableStyle objects to the GridTableStylesCollection object. При добавлении пустого объекта DataGridTableStyle в коллекцию объекты DataGridColumnStyle создаются автоматически. When you add an empty DataGridTableStyle object to the collection, DataGridColumnStyle objects are automatically generated for you. Следовательно, при попытке добавить новые объекты DataGridColumnStyle с повторяющимися значениями MappingName в объект GridColumnStylesCollection будет создано исключение. Consequently, an exception will be thrown if you try to add new DataGridColumnStyle objects with duplicate MappingName values to the GridColumnStylesCollection object.
Объявите новый стиль таблицы и задайте его имя сопоставления. Declare a new table style and set its mapping name.
Объявите новый стиль столбца и задайте его имя сопоставления и другие свойства. Declare a new column style and set its mapping name and other properties.
Вызовите метод Add объекта GridColumnStylesCollection , чтобы добавить столбец в стиль таблицы. Call the Add method of the GridColumnStylesCollection object to add the column to the table style
Вызовите метод Add объекта GridTableStylesCollection , чтобы добавить стиль таблицы в сетку данных. Call the Add method of the GridTableStylesCollection object to add the table style to the data grid.
Создание таблиц подстановки в приложениях Windows Forms Create lookup tables in Windows Forms applications
Таблица Уточняющий запрос термина описывает элементы управления, привязанные к двум связанным таблицам данных. The term lookup table describes controls that are bound to two related data tables. Эти элементы управления «Уточняющий запрос» отображают данные из первой таблицы на основе значения, выбранного во второй таблице. These lookup controls display data from the first table based on a value selected in the second table.
Таблицы подстановки можно создать, перетащив главный узел родительской таблицы (из окна Источники данных) на элемент управления в форме, который уже привязан к столбцу в связанной дочерней таблице. You can create lookup tables by dragging the main node of a parent table (from the Data Sources window) onto a control on your form that is already bound to the column in the related child table.
Например, рассмотрим таблицу Orders в базе данных Sales. For example, consider a table of Orders in a sales database. Каждая запись в Orders таблице включает объект CustomerID , указывающий, какой клиент поместил заказ. Each record in the Orders table includes a CustomerID , indicating which customer placed the order. CustomerID — Это внешний ключ, указывающий на запись клиента в Customers таблице. The CustomerID is a foreign key pointing to a customer record in the Customers table. В этом сценарии вы развернете Orders таблицу в окне Источники данных и присвойте главному узлу сведения. In this scenario, you expand the Orders table in the Data Sources window and set the main node to Details. Затем задайте CustomerID для столбца значение ComboBox (или любой другой элемент управления, поддерживающий привязку уточняющего запроса) и перетащите Orders узел на форму. Then, set the CustomerID column to use a ComboBox (or any other control that supports lookup binding), and drag the Orders node onto your form. Наконец, перетащите Customers узел на элемент управления, привязанный к связанному столбцу — в данном случае — к ComboBox CustomerID столбцу. Finally, drag the Customers node onto the control that is bound to the related column — in this case, the ComboBox bound to the CustomerID column.
Привязка элемента управления «Уточняющий запрос» To databind a lookup control
Откройте проект, откройте окно Источники данных , выбрав Просмотреть > другие > Источники данных Windows. With your project open, open the Data Sources window by choosing View > Other Windows > Data Sources.
Для таблиц подстановки необходимо, чтобы в окне Источники данных были доступны две связанные таблицы или объекты. Lookup tables require that two related tables or objects are available in the Data Sources window. Дополнительные сведения см. в разделе связи в наборах данных. For more information, see Relationships in datasets.
Разверните узлы в окне Источники данных , пока не увидите родительскую таблицу и все ее столбцы, а также связанную дочернюю таблицу и все ее столбцы. Expand the nodes in the Data Sources window until you can see the parent table and all of its columns, and the related child table and all of its columns.
Узел дочерней таблицы — это узел, который отображается как развертываемый дочерний узел в родительской таблице. The child table node is the node that appears as an expandable child node in the parent table.
Измените тип перетаскивания дочерней таблицы на Details , выбрав сведения из списка элементов управления в узле дочерней таблицы. Change the drop type of the child table to Details by selecting Details from the control list on the child table’s node. Дополнительные сведения см. в разделе Установка элемента управления, создаваемого при перетаскивании из окна Источники данных. For more information, see Set the control to be created when dragging from the Data Sources window.
Нахождение узла, связывающего две таблицы ( CustomerID узел из предыдущего примера). Locate the node that relates the two tables (the CustomerID node in the previous example). Измените тип перетаскивания на, ComboBox выбрав поле со списком в списке элементов управления. Change its drop type to a ComboBox by selecting ComboBox from the control list.
Перетащите главный узел дочерней таблицы из окна Источники данных на форму. Drag the main child table node from the Data Sources window onto your form.
Элементы управления с привязкой к данным (с описательными метками) и панель инструментов ( BindingNavigator ) отображаются в форме. Databound controls (with descriptive labels) and a tool strip (BindingNavigator) appear on the form. Набор данных, TableAdapter, BindingSource и BindingNavigator отображается в области компонентов. A DataSet, TableAdapter, BindingSource, and BindingNavigator appear in the component tray.
Теперь перетащите главный узел родительской таблицы из окна Источники данных непосредственно в элемент управления Уточняющий запрос ( ComboBox ). Now, drag the main parent table node from the Data Sources window directly onto the lookup control (the ComboBox).
Привязки подстановки теперь установлены. The lookup bindings are now established. Конкретные свойства, заданные для элемента управления, см. в следующей таблице. Refer to the following table for the specific properties that were set on the control.
Создание таблицы
Нужно составить таблицу с некоторым кол-вом столбцов и строк, которые определяются в форме (не в той, где будет таблица). Я пробовал сначала как элемент выставить datagridview, спрятать его, а по нажатию кнопки показывать с составленной таблицей, но таблица почему-то не составляется, как Datasourse передается Datatable. Не ругайтесь)
Создание хэш-таблицы
Нужно создать хэш-таблицу. Доступ к данным должен осуществляться с помощью хэш-функции. Хотелось.
Создание сложной таблицы из datagridview
Здравствуйте. Я совсем новый человек в программировании, только учусь. Пытался создать тамблицу.
Создание таблицы для расписания
Добрый день уважаемые форумчане. Необходимо создать таблицу для составления расписания.
Создание папок и файлов из таблицы
Добрый день! Можно ли из таблицы по выбраной строке создать папку и в этой папке создать файл по.
Заказываю контрольные, курсовые, дипломные и любые другие студенческие работы здесь или здесь.
Создание таблицы для многомерного куба
Добрый день участники форума! Подскажите пожалуйста, как создать фот такую таблицу, из каких.
Создание таблицы-контейнера из определенной области формы
Пишу компонент который может держать в себе другие и в runtime режиме может менять размеры.
Создание таблицы, заполняемой разными (четырьмя) цветами.
Подскажите, с помощью какого элемента (элементов) создавать похожую на предоставленую во вложении.
Создание простой таблицы с двумя столбцами (с привязкой)
Добрый день есть список обьектов (List Scripts ) и есть DataGridView (dataGridScripts).
Практическое руководство. Создание таблицы подстановок с помощью компонента BindingSource в формах Windows Forms How to: Create a Lookup Table with the Windows Forms BindingSource Component
Таблица подстановки — это таблица данных, в одном из столбцов которой отображаются данные из записей в связанной таблице. A lookup table is a table of data that has a column that displays data from records in a related table. В следующих процедурах для отображения поля с отношением по внешнему ключу от родительской к дочерней таблице используется элемент управления ComboBox. In the following procedures, a ComboBox control is used to display the field with the foreign-key relationship from the parent to the child table.
Чтобы вы могли представить это отношение, приведем пример родительской и дочерней таблицы. To help visualize these two tables and this relationship, here is an example of a parent and child table:
CustomersTable (родительская таблица) CustomersTable (parent table)
CustomerID CustomerID | CustomerName CustomerName |
---|---|
712 712 | Павел Кох Paul Koch |
713 713 | Тамара Иванова Tamara Johnston |
OrdersTable (дочерняя таблица) OrdersTable (child table)
OrderID OrderID | OrderDate OrderDate | CustomerID CustomerID |
---|---|---|
903 903 | 12 февраля 2004 г. February 12, 2004 | 712 712 |
904 904 | 13 февраля 2004 г. February 13, 2004 | 713 713 |
В данном случае одна таблица, CustomersTable, содержит актуальную информацию, которую необходимо отобразить и сохранить. In this scenario, one table, CustomersTable, stores the actual information you want to display and save. Для экономии места в таблице опущены пояснения. But to save space, the table leaves out data that adds clarity. Другая таблица, OrdersTable, содержит только внешнюю информацию о том, какой номер идентификатора клиента соответствует тем или иным данным и идентификатору заказа. The other table, OrdersTable, contains only appearance-related information about which customer ID number is equivalent to which order date and order ID. При этом имена клиентов не указываются. There is no mention of the customers’ names.
Чтобы создать таблицу подстановки, в элементе управления ComboBox устанавливаются четыре важных свойства. Four important properties are set on the ComboBox Control control to create the lookup table.
Свойство DataSource содержит имя таблицы. The DataSource property contains the name of the table.
Свойство DisplayMember содержит столбец данных таблицы, из которого нужно взять текст для элемента управления (имя клиента). The DisplayMember property contains the data column of that table that you want to display for the control text (the customer’s name).
Свойство ValueMember содержит столбец данных таблицы, в которой хранится информация (номер идентификатора в родительской таблице). The ValueMember property contains the data column of that table with the stored information (the ID number in the parent table).
Свойство SelectedValue предоставляет значение подстановки для дочерней таблицы на основании свойства ValueMember. The SelectedValue property provides the lookup value for the child table, based on the ValueMember.
Представленные ниже процедуры показывают, как разместить форму в виде таблицы подстановки и привязать данные к ее элементам управления. The procedures below show you how to lay out your form as a lookup table and bind data to the controls on it. Для успешного завершения процедур необходим источник данных с родительской и дочерней таблицами, связанными по внешнему ключу, как это уже говорилось выше. To successfully complete the procedures, you must have a data source with parent and child tables that have a foreign-key relationship, as mentioned previously.
Создание пользовательского интерфейса To create the user interface
Перетащите элемент управления из панели элементов на ComboBox форму. From the ToolBox, drag a ComboBox control onto the form.
Этот элемент управления будет отображать столбец из родительской таблицы. This control will display the column from parent table.
Перетащите другие элементы управления для отображения сведений из дочерней таблицы. Drag other controls to display details from the child table. Формат данных в таблице следует определить, исходя из выбранных элементов управления. The format of the data in the table should determine which controls you choose. Дополнительные сведения см. в разделе Функциональная классификация элементов управления Windows Forms. For more information, see Windows Forms Controls by Function.
Перетащите в форму элемент управления BindingNavigator. Это позволит перемещаться по данным в дочерней таблице. Drag a BindingNavigator control onto the form; this will allow you to navigate the data in the child table.
Подключение к данным и их привязка к элементам управления To connect to the data and bind it to controls
Выберите элемент управления ComboBox и нажмите на глиф «Быстрые действия», чтобы открыть одноименное диалоговое окно. Select the ComboBox and click the Smart Task glyph to display the Smart Task dialog box.
Выберите элемент Использовать элементы, привязанные к данным. Select Use data bound items.
Щелкните стрелку рядом с раскрывающимся списком Источник данных. Click the arrow next to the Data Source drop-down box. Если источник данных ранее был настроен для проекта или формы, он отобразится. В противном случае выполните следующие действия (в этом примере используются таблицы Customers и Orders учебной базы данных Борей, а ссылки на них приводятся в круглых скобках). If a data source has previously been configured for the project or form, it will appear; otherwise, complete the following steps (This example uses the Customers and Orders tables of the Northwind sample database and refers to them in parentheses).
Щелкните элемент Добавить источник данных проекта, чтобы подключиться к данным и создать источник данных. Click Add Project Data Source to connect to data and create a data source.
На странице приветствия Мастер настройки источника данных нажмите кнопку Далее. On the Data Source Configuration Wizard welcome page, click Next.
На странице Выбор типа источника данных выберите элемент База данных. Select Database on the Choose a Data Source Type page.
На странице Выбор подключения к базе данных выберите тип подключения данных из списка доступных подключений. Select a data connection from the list of available connections on the Choose Your Data Connection page. Если необходимое подключение данных недоступно, выберите элемент Создать подключение, чтобы создать новое подключение данных. If your desired data connection is not available, select New Connection to create a new data connection.
Нажмите кнопку Да, сохранить подключение, чтобы сохранить строку подключения в файле конфигурации приложения. Click Yes, save the connection to save the connection string in the application configuration file.
Выберите объекты базы данных, чтобы перенести их в приложение. Select the database objects to bring into your application. В данном случае выберите родительскую и дочернюю таблицы (например, таблицы Customers и Orders) с отношением по внешнему ключу. In this case, select a parent table and child table (for example, Customers and Orders) with a foreign key relationship.
Если необходимо, замените имя набора данных по умолчанию. Replace the default dataset name if you want.
Нажмите кнопку Готово. Click Finish.
В раскрывающемся списке Отобразить участника выберите имя столбца (например, ContactName) для его отображения в поле со списком. In the Display Member drop-down box, select the column name (for example, ContactName) to be displayed in the combo box.
В раскрывающемся списке Значение участника выберите столбец (например, CustomerID), чтобы выполнить операции подстановки в дочерней таблице. In the Value Member drop-down box, select the column (for example, CustomerID) to perform the lookup operation in the child table.
В раскрывающемся списке Выбранное значение перейдите к элементу Источники данных проекта и только что созданному набору данных, который содержит родительскую и дочернюю таблицы. In the Selected Value drop-down box, navigate to Project Data Sources and the dataset you just created that contains the parent and child tables. Выберите такое же свойство дочерней таблицы, которое является значением участника родительской таблицы (например, Orders.CustomerID). Select the same property of the child table that is the Value Member of the parent table (for example, Orders.CustomerID). Будут созданы и добавлены в форму соответствующие BindingSource, набор данных и компоненты адаптера таблицы. The appropriate BindingSource , data set, and table adapter components will be created and added to the form.
Свяжите элемент управления BindingNavigator с элементом BindingSource дочерней таблицы (например, OrdersBindingSource ). Bind the BindingNavigator control to the BindingSource of the child table (for example, OrdersBindingSource ).
Свяжите элементы управления, кроме ComboBox и BindingNavigator, с полями сведений из элемента BindingSource дочерней таблицы (например, OrdersBindingSource ), которые необходимо отобразить. Bind the controls other than the ComboBox and BindingNavigator control to the details fields from the child table’s BindingSource (for example, OrdersBindingSource ) that you want to display.