- Download source code — 232.7 KB
Introduction
It is often desirable to show different data in a Microsoft Access Form
. This would be done using a Subform
. There are some choices.
The normal solution is to have multiple Subform controls on a From and make only one visible. One of the things I dislike about this solution is that it clutters up the Access project with all those Form
objects, and there is no way to organize all these modules using objects. Using a Subform
is the default when the desired view is a DataSheet
view; as far as I can tell, there is no particular advantage of building a Form
that is to be displayed in a Subform
only in DataSheet
view. An advantage of using a Form
is that then only the fields that have associated controls will be visible, but this could also be accomplished in a query by deselecting the Show
(same as not including them in the Select
part of the SQL clause), but this is only possible in a Query
. A disadvantage of using a form and that is that if there are field changes in the underlying Table
/Query
, it has to be changed in Form
.
One of the cases where it is very desirable to have a dynamic view is to display data that changes dynamically, like when different Excel spreadsheets are imported into the same temporary Table
, and columns are different.
The Code
Below is shown the code behind an Option
button that changes the SourceObject
of a Subform
to a Table
and a Query
:
Private Sub optionShowQuery_Click() subFormData.SourceObject = "Query.TablesJoined" optionShowTable = False optionShowQuery = True End Sub Private Sub optionShowTable_Click() subFormData.SourceObject = "Table.Table_Countries" optionShowTable = True optionShowQuery = False End Sub
Initial Form
Show Table Selected
Show Query Selected
Gotchas
There are three buttons on the Form
. The first one will delete all records from the Table
, and the second will replace the records in the Table
from a backup Table
. If the first button in pressed (“Delete Table Contents”), in a couple of seconds, all the fields displayed will change to the “#Deleted”. Then, when the second button is pressed (“Replace Table Contents”), there will be no change. The last button, “Requery”, for force the SubForm
to do a requery of the data. This will result in the actual content of the Table being displayed.
This means that changes in the underlying data do not appear automatically in real time, and that to get this data, a Requery
on the SubForm
will have to be performed.
View after Table data deleted
History
- 12th September, 2018: Initial version
Has been working as a C# developer on contract for the last several years, including 3 years at Microsoft. Previously worked with Visual Basic and Microsoft Access VBA, and have developed code for Word, Excel and Outlook. Started working with WPF in 2007 when part of the Microsoft WPF team. For the last eight years has been working primarily as a senior WPF/C# and Silverlight/C# developer. Currently working as WPF developer with BioNano Genomics in San Diego, CA redesigning their UI for their camera system. he can be reached at qck1@hotmail.com.
- Download source code — 232.7 KB
Introduction
It is often desirable to show different data in a Microsoft Access Form
. This would be done using a Subform
. There are some choices.
The normal solution is to have multiple Subform controls on a From and make only one visible. One of the things I dislike about this solution is that it clutters up the Access project with all those Form
objects, and there is no way to organize all these modules using objects. Using a Subform
is the default when the desired view is a DataSheet
view; as far as I can tell, there is no particular advantage of building a Form
that is to be displayed in a Subform
only in DataSheet
view. An advantage of using a Form
is that then only the fields that have associated controls will be visible, but this could also be accomplished in a query by deselecting the Show
(same as not including them in the Select
part of the SQL clause), but this is only possible in a Query
. A disadvantage of using a form and that is that if there are field changes in the underlying Table
/Query
, it has to be changed in Form
.
One of the cases where it is very desirable to have a dynamic view is to display data that changes dynamically, like when different Excel spreadsheets are imported into the same temporary Table
, and columns are different.
The Code
Below is shown the code behind an Option
button that changes the SourceObject
of a Subform
to a Table
and a Query
:
Private Sub optionShowQuery_Click() subFormData.SourceObject = "Query.TablesJoined" optionShowTable = False optionShowQuery = True End Sub Private Sub optionShowTable_Click() subFormData.SourceObject = "Table.Table_Countries" optionShowTable = True optionShowQuery = False End Sub
Initial Form
Show Table Selected
Show Query Selected
Gotchas
There are three buttons on the Form
. The first one will delete all records from the Table
, and the second will replace the records in the Table
from a backup Table
. If the first button in pressed (“Delete Table Contents”), in a couple of seconds, all the fields displayed will change to the “#Deleted”. Then, when the second button is pressed (“Replace Table Contents”), there will be no change. The last button, “Requery”, for force the SubForm
to do a requery of the data. This will result in the actual content of the Table being displayed.
This means that changes in the underlying data do not appear automatically in real time, and that to get this data, a Requery
on the SubForm
will have to be performed.
View after Table data deleted
History
- 12th September, 2018: Initial version
Has been working as a C# developer on contract for the last several years, including 3 years at Microsoft. Previously worked with Visual Basic and Microsoft Access VBA, and have developed code for Word, Excel and Outlook. Started working with WPF in 2007 when part of the Microsoft WPF team. For the last eight years has been working primarily as a senior WPF/C# and Silverlight/C# developer. Currently working as WPF developer with BioNano Genomics in San Diego, CA redesigning their UI for their camera system. he can be reached at qck1@hotmail.com.
Access для Microsoft 365 Access 2021 Access 2019 Access 2016 Access 2013 Access 2010 Access 2007 Еще…Меньше
Применение
Объект Form |
Объект Report |
Свойство RecordSource (Источник записей) используется для указания источника данных для форма или отчет. Возвращает доступное для чтения и записи значение типа String.
выражение.RecordSource
выражение — обязательный аргумент. Выражение, которое возвращает один из объектов в списке «Применяется к».
Замечания
Значением свойства RecordSource может быть имя таблицы, имя запроса или инструкция SQL. Например, можно использовать следующие значения:
Пример значения |
Описание |
Employees |
Имя таблицы, указывающее в качестве источника данных таблицу Employees. |
SELECT Orders!OrderDate FROM Orders; |
Инструкция SQL, указывающая в качестве источника данных поле OrderDate в таблице Orders. Вы можете связать элемент управления в форме или отчете с полем OrderDate в таблице Orders путем установки значения OrderDate для свойства ControlSource элемента управления. |
Примечание: Свойство RecordSource можно настроить с помощью Окно свойств формы или отчета, макрос или кода Visual Basic для приложений (VBA).
В VBA для задания значения свойства используется строковое выражение.
Примечание: Изменение источника записи открытой формы или отчета приводит к автоматическому повторному запросу исходных данных. Если свойство Recordset задается в процессе выполнения, свойство RecordSource обновляется.
После создания формы или отчета можно изменить их источник данных, настроив свойство RecordSource. Кроме того, свойство RecordSource удобно использовать для создания формы или отчета, предназначенных для многократного использования. Например, вы можете создать форму со стандартной структурой, а затем скопировать эту форму и изменить свойство RecordSource для отображения данных из другой таблицы, запроса или инструкции SQL.
Ограничив число записей, содержащихся в источнике записей формы, можно повысить производительность, особенно если приложение работает в сети. Например, в качестве значения свойства RecordSource можно указать инструкцию SQL, возвращающую одну запись, и менять источник записей формы в зависимости от условий, выбранных пользователем.
Пример
В следующем примере в качестве значения свойства RecordSource формы задана таблица Customers.
Forms!frmCustomers.RecordSource = «Customers»
В следующем примере источник записей формы для единственной записи в таблице Customers меняется в зависимости от названия компании, выбранного в поле со списком cmboCompanyName. Поле со списком заполняется с помощью инструкции SQL, возвращающей код клиента (в присоединенном столбце) и название компании. Код клиента относится к текстовому типу данных.
Sub cmboCompanyName_AfterUpdate()
Dim strNewRecord As String
strNewRecord = "SELECT * FROM Customers " _
& " WHERE CustomerID = '" _
& Me!cmboCompanyName.Value & "'"
Me.RecordSource = strNewRecord
End Sub
Нужна дополнительная помощь?
1 / 1 / 0 Регистрация: 02.06.2009 Сообщений: 104 |
|
1 |
|
Как программно изменять источник записей у формы20.07.2009, 14:17. Показов 7996. Ответов 4
К примеру если флажок=true то источник строк у формы изменять?
__________________
0 |
БурундукЪ 10026 / 2615 / 84 Регистрация: 17.02.2009 Сообщений: 10,364 |
||||
20.07.2009, 15:07 |
2 |
|||
1 |
1 / 1 / 0 Регистрация: 02.06.2009 Сообщений: 104 |
|
21.07.2009, 09:07 [ТС] |
3 |
Есть ли аналогично Recordsource для формы, команда для поля формы(изменить параметр «данные» поля)?
0 |
paladin 286 / 186 / 7 Регистрация: 25.02.2009 Сообщений: 589 |
|
21.07.2009, 09:16 |
4 |
Есть. Осталось только найти ее в списке свойств поля и нажать F1.
0 |
1 / 1 / 0 Регистрация: 02.06.2009 Сообщений: 104 |
|
21.07.2009, 09:31 [ТС] |
5 |
Есть. Осталось только найти ее в списке свойств поля и нажать F1. Справка на английском, тяжело все понять, раз есть такая команда, значит найду Добавлено через 8 минут 35 секунд
0 |