C#. Windows Forms. Databases. Course work. Development of a program for accounting of material assets. The Microsoft Access database. Windows Forms application




C#. Course work. Development of a program for accounting of material assets. The Microsoft Access database. Windows Forms application

In the course work describes a step-by-step process of creating a program for accounting of material assets (inventory). An approach to develop of an application is presented, which interacts with the database on a standalone level using Microsoft Visual Studio tools.

Using this example, you can create your own applications that operate with Microsoft Access database, using MS Visual Studio tools. The example that is demonstrated in this topic can also be suitable for operating databases of other providers, for example, Microsoft SQL Server, Oracle, etc. since working with components on an disconnected layer is no different from the work described in this topic.

The similar term papers:

This work demonstrates the availability of powerful tools for working with databases in MS Visual Studio. The interaction between the visual controls and the database is realized with the help of the appropriate settings, without the programming of SQL queries. This, in turn, minimizes the writing of program code by the programmer, since all work on information output and processing of database tables is performed by the system.


Contents


Search other websites:

Task

Develop a program for the automated accounting of material assets. Use the Microsoft Access database. The program (application) must be created using the Windows Forms Application template.

The database was previously created by means of Microsoft Access and has the name Account. Archive with the database file Account.mdb can be downloaded here.

The Account database consists of two Worker and Account tables. The Worker table describes the general data about the employee of the enterprise or organization. The Account table describes a list of material assets that are registered for a specific employee. The tables are linked by the ID_Worker field.

The structure of the Worker table.

The Worker table

The structure of the Account table.

The Account table

The diagram of the connection between the tables is shown in Figure 1.

Database Microsoft Access. The scheme of relationships between tables

Figure 1. The scheme of relationships between tables

 


Additional information

The displaying of database tables and the interaction with the user are performed using the DataGridView control.

After binding of the table to the database system generates three objects with names

  • DataBaseNameDataSet
  • TableNameBindingSource
  • TableNameTableAdapter

where

  • prefix DataBaseName… is the name of the database. In our case, the name AccountDataSet is generated for the Account database;
  • the prefix tableName… is the name of the table in the database. In our case, two objects with the names workerTableAdapter, workerBindingSource will be created for the Worker table.

Most of the work to configure and organize interaction with the database is carried out with the help of these objects. The main idea of this course work is to make maximum use of the capabilities of these objects. As it will be shown below, you do not need to connect the System.Data.OleDb namespace, since all the routine work is performed by the Microsoft Visual Studio object interface.

 


Instructions

1. Creating a project

Run MS Visual Studio. Create an application using the Windows Forms Application template. A detailed example of creating an application using the Windows Forms Application template is described in the topic:

Creating a new project is done by the command

File->New Project...

The following settings are set in the “New Project” window (Figure 2):

  • in the “Installed Templates” field, select “Visual C #”;
  • in the list of Visual C# templates, select Windows Forms Application;
  • in the “Location:” field, you must specify the folder in which the project will be placed (using the “Browse …” button). For example “D:\Programs\C_Sharp\Oblik01”;
  • in the field “Name:” you need to specify the name of the newly created project. In our case this is Oblik01.

Microsoft Visual Studio. New Project window. Settings window when creating a project

Figure 2. Settings window when creating a project

After selecting “OK”, a new form of application will be created with the name ‘Form1’.

 

2. Connecting the database “Account.mdb” to the application

At this point, you need to copy the database “Account.mdb” to the folder where the project files are located. Archive with the previously created database file can be downloaded here.

In our case, after copying the database file may have the following full name:

D:\Programs\Oblik01\Account.mdb

or

D:\Programs\Oblik01\Oblik01\Account.mdb

In this case, we will not go into details of connecting the database file to the application. A detailed example of connecting the database Account.mdb to the application is given in the topic:

The database file is connected according to the wizard principle. In the step-by-step process, when selecting database tables, you must select all the tables (Worker, Account) and views (AccountQuery, AccountQueryCalc, QueryWorker).

The name of the data source remains the default – AccountDataSet.

After connecting the database file to the application, the view of the Server Explorer window will look like shown in Figure 3.

MS Visual Studio. Window of the Server Explorer utility after connecting the database Account.mdb

Figure 3. Window of the Server Explorer utility after connecting the database Account.mdb

 

3. Designing the main form of application

At the moment there is an empty form of application and connection to the Account.mdb database. The default form name is Form1.

 3.1. Configuring the common properties of the main form Form1

To configure the general properties of the form, you must activate (highlight) the form and perform the appropriate actions in the Properties window (F4 key). Configure the following properties of the form:

  • property Text = “Inventory accounting” (Figure 4);
  • in the tab Size, property Width = 800;
  • in the tab Size, property Height =600;
  • property MaximizeBox = False. The button of transfer from maximize mode to normal mode will deactivated.

C#. Windows Forms Application. Setting the properties of 'Form1' form

Figure 4. Setting the properties of ‘Form1’ form

 

3.2. Designing the menu. ‘MenuStrip’ control

At this stage, the command menu of the main form of application is projected. To create a menu, you must use the MenuStrip control. After placing on the form, a menuStrip1 object is created. This object corresponds to the main menu (Figure 5).

C#. Windows Forms Application template. The MenuStrip control

Figure 5. The MenuStrip control

In this topic, the details of the development of the menu are omitted. A more detailed example of creating the main menu is described in the topic:

A list of commands is created in the menu, as shown in Figures 6-7.

C#. Windows Forms Application template. List of 'Worker' menu commands

Figure 6. List of ‘Worker’ menu commands

The Worker menu contains commands for adding, deleting and editing the Worker table.

C#. Windows Forms Application template. The list of 'Inventory' menu commands

Figure 7. The list of ‘Inventory’ menu commands

The Inventory menu contains commands for adding, deleting and editing the Account table.

 

3.3. Placement of controls such as Label, Button, TextBox, DataGridView on the form

From the Toolbox toolbar select and place the following controls:

  • three controls of the Label type for displaying information messages. Automatically, three objects will be created with the names label1, label2, label3;
  • six Button controls for quick menu commands. Automatically six objects with the names button1, button2, button3, button4, button5, button6 are created;
  • one TextBox control. This will display the filter text for the ‘Worker’ table output. An object is created with the name textBox1;
  • two controls of DataGridView type. Two objects are created with the names dataGridView1, dataGridView2. These objects are used to display data in the Worker and Account tables.

After placing the controls, the form will have an approximate view as shown in Figure 8.

C#. Windows Forms Application template. View of the main form after placement of controls

Figure 8. View of the main form after placement of controls

 

3.4. Setting the dataGridView1 control corresponding to the Worker table
3.4.1. Connecting the database table ‘Worker’

The Worker table is connected to the application in the standard way. The Worker table will be displayed in the dataGridView1 control.

To start the connection process, you must first activate dataGridView1. Then select the arrow to the right as shown in Figure 9. The “DataGridView Tasks” menu is displayed.

C#. Windows Forms Application. Menu 'DataGridView Tasks' of the dataGridView1 control

Figure 9. Menu ‘DataGridView Tasks’ of the dataGridView1 control

In the “DataGridView Tasks” menu, you must activate the “Choose Data Source:” drop-down submenu and expand the list of data sources as shown in Figure 10. Select the Worker table in the list.

C#. Windows Forms Application. Selecting the AccountDataSet data source and the Worker table

Figure 10. Selecting the AccountDataSet data source and the Worker table

After selecting the Worker table, the dataGridView1 control window will display the names of the fields of the Worker table (Figure 11). Also, three accountDataSet, workerBindingSource, workerTableAdapter objects are created to interact with the Worker table of the database and display it in the dataGridView1.

C#. Windows Forms application template. The dataGridView1 view after selecting the data source

Figure 11. The dataGridView1 view after selecting the data source (Worker table). The objects accountDataSet, workerBindingSource, workerTableAdapter

 

3.4.2. Controls accountDataSet, workerBindingSource, workerTableAdapter

Figure 11 shows that the system will create three accountDataSet, workerBindingSource, workerTableAdapter objects after selecting the data source. The data source is the Worker table. Using these objects, you can organize interaction with the Worker table of the database (shown below).

If you now run the application for execution, you can see that the data of the Worker table is displayed in the dataGridView1.



 

3.4.3. Changes in the main event’s Load event handler. The text of the Form1_Load() method

After selecting the data source in dataGridView1, the code of the event handler Form1_Load() is changed. The text of the event handler is as follows:

private void Form1_Load(object sender, EventArgs e)
{
    // TODO: This line of code loads data into the 'accountDataSet.Worker' table. You can move, or remove it, as needed.
    this.workerTableAdapter.Fill(this.accountDataSet.Worker);
}

The Fill() method of the workerTableAdapter object is called. In the future, this method will be used to display data from the Worker table in the dataGridView1 control.

 

3.4.4. Customizing the view of columns of the DataGridView1 control

In this step, you configure the appearance of dataGridView1. The Microsoft Visual Studio system provides a fairly wide range of options for customizing the table that is displayed in the DataGridView. You can configure the following basic visual elements:

  • table columns names;
  • table columns font;
  • the background color and the text color of the table columns;
  • font of each header of the table columns;
  • background color and text color of table headings;
  • ways to align in the cells of the table;
  • ways of alignment in the headers of the table;
  • the ability to display (hide) the specified columns of the table;
  • other additional features.

In our case, you need to configure the following common properties of dataGridView1:

  • property MultiSelect = False (disable the selection of multiple lines);
  • ReadOnly = True. It is forbidden to edit cells dataGridView1 directly. Changing the values in the cells will occur through special windows (forms);
  • AllowUserToDeleteRows = False. It is forbidden to delete lines by pressing the Del key;
  • SelectionMode = FullRowSelect. A whole line is selected, and not a single cell of the line.

 

3.4.4.1. Group configuring of all column headers. The ColumnHeadersDefaultCellStyle property

Group setting of header parameters of all columns is performed using the ColumnHeaderDefaultCellStyle property. This property is used if several columns of the table have identical design requirements (for example, font, text color, alignment).

If you need to individually customize the kind of columns you need, then in MS Visual Studio, you use a special Edit Columns window (see next paragraph).

This property allows you to configure the default appearance of all column headers in the DataGridView table (Figure 12).

C#. Windows Forms Application. The ColumnHeadersDefaultCellStyle property

Figure 12. The ColumnHeadersDefaultCellStyle property

To configure the ColumnHeadersDefauleCellStyle property you need:

  • activate the dataGridView1 control;
  • select the “…” button opposite the ColumnHeadersDefaultCellStyle property (Figure 12). This will open the standard CellStyleBuilder window (Figure 13).

C#. Microsoft Visual Studio. The "CellStyle Builder" window. Customizing the view of cells

Figure 13. The “CellStyle Builder” window. Customizing the view of cells

For the header, you can use the following properties in this window:

  • BackColor – background color;
  • Font – font. When you select the “…” button, a standard Windows window opens to select the desired font;
  • ForeColor – font color;
  • Format – numeric output format. Various formats for representing numbers in cells are proposed: NoFormatting, Numeric, Currency, DateTime, Scientific, Custom. In our case, the column headers contain only text, so you do not need to change this property;
  • Alignment – align text in the header horizontally and vertically;
  • Padding – padding in pixels between the text and the frame in which this text fits.

At the bottom of the window is the Preview group. In the Preview group, you can review the current display of cells in on-the-fly mode.

In our case, you need to configure the following ColumnHeadersDefaultCellStyle properties:

  • property Alignment = MiddleCenter;
  • property Font.Bold = true.

 

3.4.4.2. Set the DefaultCellStyle template for a generalized display of data in the columns dataGridView1

The DefaultCellStyle property (Figure 14) allows you to set common (common for all) settings for the cells (rows) of all the columns of the table that are displayed in the DataGridView. If some lines have different settings, then they can be changed individually (see next paragraph).

C#. Windows Forms. DataGridView control. Calling the DefaultCellStyle property

Figure 14. Calling the DefaultCellStyle property

The work on setting the DefaultCellStyle property is exactly the same as the ColumnHeadersDefaultCellStyle property, which is described in the previous paragraph. Therefore, to consider this property additionally does not make sense.

 

3.4.4.3. Customizing the view of a specified column of table

There are times when the table column has unique display options. In this case, you need to call a special “Edit Columns” window for the DataGridView control. To call the “Edit Columns” window, you need to perform the following actions (Figure 15):

  • activate the dataGridView1 control. A context menu opens;
  • in the context menu select the command “Edit Columns …”.

C#. Windows Forms Application. Call the Edit Columns window

Рис. 15. Call the Edit Columns window

After calling the window “Edit Columns” has the view, as shown in Figure 16.

C# Windows Forms. Control DataGridView. The window for configuring of each column by individually

Figure 16. The window for configuring of each column by individually

In the “Selected Column:” list, a list of the fields of the table that is displayed in the dataGridView1 is displayed. In the “Bound Column Properties” list, for each selected field, a list of available properties and their values is displayed.

By default, all columns (fields) of the table are set to the values that were set in the ColumnHeadersDefaultCellStyle properties (see the previous paragraph). In the “Edit Columns” window, only those column header settings that are unique are configured.

For each column, the “Edit Columns” window offers the following basic properties:

  • DefaultCellStyle – sets the basic parameters for the cells (rows) of the column (font, background color, alignment). To configure this property, a special “CellStyle Builder” window is called, which is described in detail in the previous paragraph.
  • HeaderText – the header text that will be displayed in the table;
  • Visible – specifies whether the column is displayed in the DataGridView;
  • MaxInputLength – the maximum number of characters that can be entered in the cells (rows) of the column;
  • ReadOnly – determines whether you can directly edit cell values in the DataGridView;
  • Resizeable – determines whether the column width can be changed directly in the DataGridView (with the mouse);
  • Name – the name of the object (variable) that corresponds to this column. This name is used in the program code;
  • ColumnType – the column type. The MS Visual Studio system offers different types of column views. The most common is the representation of the cells of the column in the form of lines of input TextBoxDataGridViewTextBoxColumn;
  • AutoSizeMode – determines whether the width of the column is expanded if the text in the column row (in pixels) has a larger width than specified in the Width property. For example, a property is useful when you want to fully display text in a column without cutting it;
  • DividerWidth – additional border width (in pixels) between the specified column and the column that is displayed on the right side.
  • MinimumWidth – minimum allowed column width in pixels;
  • Width – column width in pixels.

In our case, you need to set the following properties:

  • in the column ID_Worker property Visible = False. Because the ID_Worker field is used to bind tables, it does not make sense to display it;
  • in the WName column, property HeaderText = “Name of worker”;
  • in the WName column, property AutoSizeMode = AllCells. Now the width of the WName column will be adjusted to the width of the row, which has the maximum width (in pixels) among all rows;
  • in the WPosition column, property HeaderText = “Position”;
  • in the WPosition column, property AutoSizeMode = AllCells;
  • in the WSex column, property HeaderText = “M/F”;
  • in the WSex column, property AutoSizeMode = AllCells;
  • in the WSex column, property DefaultCellStyle.Alignment = MiddleCenter.

 

3.5. Configuring the dataGridView2 control that corresponds to the Account table
3.5.1. Binding the Account table and dataGridView2 control

The binding of the Account table to the dataGridView2 control is done in the same way as for the Worker table, which is described in paragraph 3.4.1. You must first activate dataGridView2. Then select the right arrow. In the “DataGridView Tasks” window, in the “Choose Data Source:” field, select

Other Data Sources -> Project Data Sources -> AccountDataSet -> Account

as shown in Figure 17.

C#. Windows Forms Application. Selecting the Account table in the "DataGridView Tasks" window

Figure 17. Selecting the Account table in the “DataGridView Tasks” window

After selecting the Account table, the fields of this table will be displayed in the dataGridView2 window. Also, two new accountBindingSource and accountTableAdapter objects are created (Figure 18).

C#. Windows Forms. Form view after connecting Account table to dataGridView2

Figure 18. Form view after connecting Account table to dataGridView2

 

3.5.2. The accountDataSet, accountBindingSource, accountTableAdapter objects

As with the Worker table (see section 3.4.1), after selecting the Account table as the data source, two more objects are created (Figure 18):

  • accountBindingSource – binds the database table directly to the AccountDataSet dataset (here Account is the name of the database and not the table);
  • accountTableAdapter – used to directly program the data in the table (adding rows, columns, etc.).

The accountDataSet object is common to the objects of the Worker and Account tables: workerBindingSource, workerTableAdapter, accountBindingSource, accountTableAdapter.

 

3.5.3. Changes in the Load event handler of the main form. The text of the Form1_Load() method

After associating the Account table with dataGridView2, another Fill() method is added to the text of the event handler Form_Load().

The general view of the Load event handler for the main Form1 is as follows:

private void Form1_Load(object sender, EventArgs e)
{
    // TODO: This line of code loads data into the 'accountDataSet.Account' table. You can move, or remove it, as needed.
    this.accountTableAdapter.Fill(this.accountDataSet.Account);

    // TODO: This line of code loads data into the 'accountDataSet.Worker' table. You can move, or remove it, as needed.
    this.workerTableAdapter.Fill(this.accountDataSet.Worker);
}

 

3.5.4. Configuring the view of columns dataGridView2 (table Account)

In our case, you need to configure the following common properties of dataGridView2:

  • property MultiSelect = False (disable selection of multiple rows);
  • ReadOnly = True. It is forbidden to edit dataGridView2 cells directly. Changing the values in the cells will occur through special windows (forms);
  • AllowUserToDeleteRows = False. It is forbidden to delete rows by pressing the Del key;
  • SelectionMode = FullRowSelect. A whole row is selected, and not a single cell of the row.

 

3.5.4.1. Group configuring of all column headers. The ColumnHeadersDefaultCellStyle property

Using the ColumnHeadersDefaultCellStyle property, you configure the general appearance of the default columns. This property is described in more detail in paragraph 3.4.4.1.

For ColumnHeadersDefaultCellStyle, you need to configure the following internal properties:

  • property Alignment = MiddleCenter;
  • property Bold = True.

 

3.5.4.2. Specifying a generalized display of data in the columns dataGridView2 (the DefaultCellStyle property)

In paragraph 3.4.4.2, details of the use of the DefaultCellStyle property of the dataGridView2 control are described in detail.

For the Account table, you need to set the following properties:

  • property Alignment = MiddleCenter.

 

3.5.4.3. Setting individual display options for each column of the table

Customizing the appearance of the columns dataGridView2 is carried out in the same way as dataGridView1. To do this, in design mode, you need to call the command “Edit Columns …” from the context menu dataGridView2 (see paragraph 3.4.3.3.). The properties of the following fields are set:

  • in the field ID_Account, property Visible = False (hide field);
  • in the field ID_Worker, property Visible = False;
  • in the field ANum, property HeaderText = “Number”;
  • in the field ANum, property DefaultCellStyle.Alignment = MiddleCenter;
  • in the field ANum, property AutoSizeMode = AllCells;
  • in the field ADate, property HeaderText = “Date”;
  • in the field ADate, property DefaultCellStyle.Alignment = MiddleCenter;
  • in the field ADate, property AutoSizeMode = AllCells;
  • in the field AInvNum property HeaderText = “Inv. Number”;
  • in the field AInvNum property DefaultCellStyle.Alignment = MiddleCenter;
  • in the field AInvNum property AutoSizeMode = AllCells;
  • in the field AObjName property HeaderText = “Object name”;
  • in the field AObjName property DefaultCellStyle.Alignment = MiddleLeft;
  • in the field AObjName property AutoSizeMode = AllCells;
  • in the field ACount property HeaderText = “Count”;
  • in the field ACount property DefaultCellStyle.Alignment = MiddleCenter;
  • in the field ACount property AutoSizeMode = AllCells;
  • in the field APrice property HeaderText = “Price”;
  • in the field APrice property DefaultCellStyle.Alignment = MiddleRight;
  • in the field APrice property AutoSizeMode = AllCells.

 

3.6. Creating a calculated “Sum” field in the Account table

A separate item in this topic is the addition of a calculated field. The calculated field “Sum” in the Account table can be added in various ways. For example, you can create this field with Microsoft Access and create a View. Here one of possible ways is described.

The result of the Sum field is the multiplication of the ACount and APrice fields.

 

3.6.1. Adding a ‘Sum’ calculation field to the AccountDataSet.xsd file

The AccountDataSet.xsd file displays tables (views, stored procedures, etc.) of the Account database that are connected to the accountDataSet dataset. In fact, the calculated field is created in this file.

To create a calculated field in the Account table, you need to do the following:

  • in the “Form1.cs [Design]” mode, right-click on the accountTableAdapter object. As a result, the context menu will open (Figure 19);

C#. Windows Forms. Context menu of the accountTableAdapter data adapter

Figure 19. Context menu of the accountTableAdapter data adapter

  • In the context menu, select the command “Edit Queries in DataSet Designer …”. A window will open displaying the contents of the file “AccountDataSet1.xsd” (Figure 20);

C#. Windows Forms. Displaying the Account table in the AccountDataSet.xsd file

Figure 20. Displaying the Account table in the AccountDataSet.xsd file

  • call the context menu for the Account table (Figure 21). Select Add->Column command in the menu. As a result, a new field named DataColumn1 will be created.

MS Visual Studio. Database Microsoft Access. Calling the command to add a new column

Figure 21. Calling the command to add a new column

  • select the DataColumn1 field and set the Name = “Sum” in the Properties window (Figure 22).

Database MS Access. Setting the Name property for the calculated field

Figure 22. Setting the Name property for the calculated field

  • set the Expression property to “ACount * APrice” (Figure 23). Save and close the file AccountDataSet.xsd;

MS Visual Studio. Database MS Access. The 'Expression' property of the additional 'Sum' field

Figure 23. The ‘Expression’ property of the additional ‘Sum’ field

  • set the property DataType = System.Double (Figure 24). This is necessary to conveniently display the results, that end with a zero value. That is, the number 2.3 will be displayed as 2.30.

MS Visual Studio. MS Access database. The DataType property

Figure 24. The DataType property

After that, you can save the project and close the AccountDataSet.xsd file.

 

3.6.2. Connecting the created Sum field to the dataGridView2

The next step is to connect the created Sum field to the list of dataGridView2 fields to display it. To display the Sum field in the dataGridView1 need to perform the following steps:

  • go to the form design mode “Form1.cs [Design]”. Make a right mouse click on the dataGridView2 control. In the context menu select the command “Edit Columns …” (Figure 25). This will open the “Edit Columns” window;

C#. Control DataGridView. The dataGridView2 context menu. Calling the command "Edit Columns ..."

Figure 25. The dataGridView2 context menu. Calling the command “Edit Columns …”

  • In the Edit Columns window, select the command “Add …” (Figure 26). The “Add Column” window will open.

C#. MS Visual Studio. Control DataGridView. The "Edit Columns" window. The "Add..." command

Figure 26. The “Edit Columns” window. The “Add…” command

  • In the “Add Column” window in the “Databound column” list, select the “Sum” field (Figure 27). You can also change the “Header text:” field. After selecting the Add button, you will go to the previous Edit Columns window;

MS Visual Studio. The "Add Column" window. Selecting the Sum field to display in the dataGridView2

Figure 27. The “Add Column” window. Selecting the Sum field to display in the dataGridView2

  • In the “Edit Columns” window, the Sum field may not be in its position. Therefore, its position in the table should be corrected with the help of the up and down arrow buttons (Figure 28).

C#. Windows Forms. DataGridView control. The final formation of the calculated Sum field in the "Edit Columns" window

Figure 28. The final formation of the calculated Sum field in the “Edit Columns” window

Formation of a calculated field by means of MS Visual Studio is completed.

 

3.6.3. Setting the display of the calculated “Sum” field with an accuracy of 2 decimal places

At the moment, the calculated Sum field is displayed in an arbitrary format. It is convenient to have a mapping of this field with an accuracy of 2 decimal places. To do this, you need to do the following:

  • call the context menu of the DataGridView2 control. Select “Edit Columns …” from the menu. This will open the “Edit Columns” window;
  • in the “Edit Columns” window, activate (highlight) the “Sum” field (Figure 29). In the property list, select “…” next to the DefaultCellStyle property. The “CellStyle Builder” window will open;

C#. Windows Forms Application. DataGridView control. Calling the cell properties editing window in the "Sum" field

Figure 29. Calling the cell properties editing window in the “Sum” field

  • in the “CellStyle Builder” window, select the Format property (Figure 30). The “Format String Dialog” window will open;

C#. Windows Forms. Control DataGridView. The CellStyleBuilder window. The Format property

Figure 30. The CellStyleBuilder window. The Format property

  • in the “Format String Dialog” window several known formats are proposed for displaying monetary values. In the “Format type:” field, select the type of the Numeric format. The value of “Decimal places” = 2 (Figure 31).

C#. Windows Forms. Control DataGridView. The "Format String Dialog" window

Figure 31. The “Format String Dialog” window

After selecting OK, you will go to the previous CellStyleBuilder window. In this window, you can adjust the Alignment property to the value of MiddleRight.

The last step is to confirm to OK in all subsequent windows. After that, the calculated field “Sum” will be displayed with an accuracy of 2 decimal places.

 

3.7. Configuring the properties of the Label, Button, TextBox controls

Configure the following properties of the controls that are placed in the main form:

  • in label1 control, property Text = “Worker” (in the following label1.Text);
  • label2.Text = “Filter:”;
  • label3.Text = “Account”;
  • button1.Text = “Add…”;
  • button2.Text = “Delete”;
  • button3.Text = “Edit…”;
  • button4.Text = “Add record…”;
  • button5.Text = “Delete record”;
  • button6.Text = “Edit record…”;
  • textBox1.Text = “”.

 

3.8. General view of the form “Form1.cs” after configuring

After configuring, the view of the main form of the application is as shown in Figure 32.

C#. Windows Forms Application. Main form after configuring

Figure 33. Main form after configuring

 

4. Designing additional forms

4.1. Designing the form “FormAddWorker.cs” to add a new worker

At this stage, the form of adding information about the new worker is projected. To add a new form, you need to use the command

Project -> Add Windows Form...

A window opens in which you want to specify the name of the form file (Figure 33). In our case, the name “FormAddWorker.cs” is given.

A more detailed description of how to create a form is described in the topic:

  • An example of creating and calling a new form in C# application.

C#. Windows Forms Application. Adding a new FormAddWorker.cs form to the application

Figure 33. Adding a new FormAddWorker.cs form to the application

You need to place the following controls (Figure 34):

  • three controls of Label type. Objects with the names label1, label2, label3 are created;
  • two controls of Button type. Objects with the names button1, button2 are created;
  • one control of ComboBox type. An object with the name comboBox1 is created;
  • two controls of TextBox type. Objects with the names textBox1, textBox2 are created.

C#. Windows Forms Application template. The "FormAddWorker.cs" form

Figure 34. The “FormAddWorker.cs” form

The following properties of controls are set:

  • in the form, property Text = “Add worker”(further FormAddWorker.Text);
  • FormAddWorker.ControlBox = False;
  • FormAddWorker.StartPosition = CenterScreen;
  • FormAddWorker.FormBorderStyle = FixedDialog;
  • in the control label1, property Text = “Name of worker” (label1.Text);
  • label2.Text = “Position”;
  • label3.Text = “M/F”;
  • button1.Text = “Add”;
  • button2.Text = “Cancel”;
  • button1.DialogResult = OK;
  • button2.DialogResult = Cancel;
  • textBox1.Modifiers = Public. The textBox1 control becomes accessible from other forms and methods;
  • textBox2.Modifiers = Public;
  • comboBox1.Modifiers = Public.

In the comboBox1 control, you need to enter the strings in the Items property, as shown in Figure 35.

C#. Windows Forms Application. The Items property of the comboBox1 control

Figure 35. The Items property of the comboBox1 control

After designing, the FormAddWorker form window is shown in Figure 36.

C#. Windows Forms Application template. The FormAddWorker form

Figure 36. The FormAddWorker form

 

4.2. Designing the “FormDelWorker.cs” form of deleting worker

Based on the design of the previous form (paragraph 4.1), the form of worker deleting is projected, which is located in the FormDelWorker.cs file.

The form contains the following controls:

  • two controls of Label type. Two objects with the names label1, label2 are created;
  • two controls of Button type. Two objects with the names button1, button2 are created.

Configure the following properties of the controls:

  • FormDelWorker.Text = “Delete worker”;
  • FormDelWorker.FormBorderStyle = FixedDialog;
  • FormDelWorker.StartPosition = CenterScreen;
  • FormDelWorker.ControlBox = False;
  • label1.Text = “Delete worker. Are you sure?”;
  • label2.Modifiers = Public. This control will be visible from the main form and will be formed from it;
  • button1.Text = “OK”;
  • button1.DialogResult = OK;
  • button2.Text = “Cancel”;
  • button2.DialogResult = Cancel.

After creating and configuring the controls, the form has the view as shown in Figure 37.

C#. Windows Forms Application template. The FormDelWorker.cs form

Figure 37. The FormDelWorker.cs form

 

4.3. Designing the form “FormEditWorker.cs” editing information about the worker

FormEditWorker.cs is intended for editing information about a worker and will be called by a command

Worker->Edit...

FormEditWorker.cs is created in the same way as the previous forms. The form contains the following controls:

  • three controls of Label type. Objects with the names label1, label2, label3 are created;
  • two controls of Button type. Objects with the names button1, button2 are created;
  • one control of ComboBox type. The object with name comboBox1 is created;
  • two controls of TextBox type. Objects with the names textBox1, textBox2 are created.

The following properties of controls are set:

  • FormEditWorker.Text = “Edit worker”;
  • FormEditWorker.FormBorderStyle = FixedDialog;
  • FormEditWorker.StartPosition = CenterScreen;
  • FormEditWorker.ControlBox = False;
  • label1.Text = “Name of worker”;
  • label2.Text = “Position”;
  • label3.Text = “M/F”;
  • textBox1.Modifiers = Public;
  • textBox2.Modifiers = Public;
  • comboBox1.Modifiers = Public;
  • comboBox1.Items = { “M”, “F” };
  • button1.Text = “Edit”;
  • button2.Text = “Cancel”;
  • button1.DialogResult = OK;
  • button2.DialogResult = Cancel.

After designing, the form window looks like shown in Figure 38.

C#. Windows Forms Application template. Window for editing information about the worker

Figure 38. Window for editing information about the worker

 

4.4. Designing the form “FormAddAccount.cs” for adding the inventory

The FormAddAccount.cs form is used to add a row of inventory. The form contains the following controls:

  • 6 controls of Label type. Objects with names label1, label2, label3, label4, label5, label6 are created;
  • 6 controls of TextBox type. Objects with names textBox1, textBox2, textBox3, textBox4, textBox5, textBox6 are created;
  • 2 controls of Button type. Objects with names button1, button2 are created.

The properties of the following controls are set:

  • FormAddAccount.Text = “Add Inventory”;
  • FormAddAccount.FormBorderStyle = FixedDialog;
  • FormAddAccount.ControlBox = False;
  • FormAddAccount.StartPosition = CenterScreen;
  • label1.Text = “Number”;
  • label2.Text = “Date”;
  • label3.Text = “Inventory number”;
  • label4.Text = “Object name”;
  • label5.Text = “Count”;
  • label6.Text = “Price”;
  • button1.Text = “Add”;
  • button1.DialogResult = OK;
  • button2.Text = “Cancel”;
  • button2.DialogResult = Cancel;
  • textBox1.Modifiers = Public;
  • textBox2.Modifiers = Public;
  • textBox3.Modifiers = Public;
  • textBox4.Modifiers = Public;
  • textBox5.Modifiers = Public;
  • textBox6.Modifiers = Public.

Figure 39 shows the FormAddAccount.cs form window after configuring.

C#. Windows Forms Application template. FormAddAccount.cs window after configuring

Figure 39. FormAddAccount.cs window after configuring

 

4.5. Designing the form “FormDelAccount.cs” deleting the row of inventory

The FormDelAccount.cs form realizes a confirmation window for deleting a row of inventory. The form contains the following controls:

  • two controls of Button type (button1, button2);
  • two controls of Label type (label1, label2).

You need to configure the following properties of the controls:

  • FormDelAccount.Text = “Delete Inventory”;
  • FormDelAccount.FormBorderStyle = FixedDialog;
  • FormDelAccount.ControlBox = False;
  • FormDelAccount.StartPosition = CenterScreen;
  • label1.Text = “Are you sure you want to delete?”;
  • label2.Modifiers = Public. This row will change in the main form, so it can be visible from the outside;
  • button1.Text = “Delete”;
  • button1.DialogResult = OK;
  • button2.Text = “Cancel”;
  • button2.DialogResult = Cancel.

Figure 40 shows the general form of FormDelAccount

C#. Windows Forms. General view of FormDelAccount form

Figure 40. General view of FormDelAccount form

 

4.6. Designing the form “FormEditAccount.cs” of editing the row

FormEditAccount.cs is designed to edit the information of the current row of the Account table. The form contains the following controls:

  • 6 controls of Label type: label1, label2, label3, label4, label5, label6;
  • 6 controls of TextBox type: textBox1, textBox2, textBox3, textBox4, textBox5, textBox6;
  • 2 controls of Button type: button1, button2.

Настраиваются следующие свойства формы и элементов управления:

  • FormEditAccount.Text = “Edit Inventory”;
  • FormEditAccount.FormBorderStyle = FixedDialog;
  • FormEditAccount.ControlBox = False;
  • FormEditAccount.StartPosition = CenterScreen;
  • label1.Text = “Number”;
  • label2.Text = “Date”;
  • label3.Text = “Inventory number”;
  • label4.Text = “Object name”;
  • label5.Text = “Count”;
  • label6.Text = “Price”;
  • button1.Text = “Add”;
  • button1.DialogResult = OK;
  • button2.Text = “Cancel”;
  • button2.DialogResult = Cancel;
  • textBox1.Modifiers = Public;
  • textBox2.Modifiers = Public;
  • textBox3.Modifiers = Public;
  • textBox4.Modifiers = Public;
  • textBox5.Modifiers = Public;
  • textBox6.Modifiers = Public.

After configuring, the FormEditAccount.cs is shown in Figure 41.

C#. Windows Forms. The FormEditAccount.cs form

Figure 41. The FormEditAccount.cs form

 

5. Implementation of the program code

It remains only to write the code of the event handlers.

5.1. Programming event handlers for the main form Form1
5.1.1. Programming the Click and CellEnter events of the dataGridView1 control. The Filter property. Consideration for the relationship between tables when they are displayed

At the moment, all the data of the Worker and Account tables are displayed. However, in our case, you need to correct the data displaying in the tables according to the following requirement.

If you select an employee in the Worker table, then the Account table should display data that only affects this worker. As you know, the Worker and Account tables are binden to each other by the ID_Worker field. This means that the Account table must display data that corresponds to the ID_Worker value of the active (highlighted) row of the Worker table.

In our case, you need to program two events for the dataGridView1 control:

  • the Click event (Figure 43). This event is generated when the user clicks on a certain row;
  • the CellEnter event (Figure 44). This event is generated when the table row receives the input focus.

C#. Windows Forms. The Click event of the dataGridView1 control

Figure 43. The Click event of the dataGridView1 control

C#. Windows Forms Application template. The CellEnter event of the dataGridView1 control

Figure 44. The CellEnter event of the dataGridView1 control

In this topic, the process of programming the event handler is omitted. A more detailed example of event programming is described in the topic:

The text of the event handlers is as follows:

private void dataGridView1_Click(object sender, EventArgs e)
{
    // create a filter that will output to dataGridView2 what you need
    int id;
    int index;

    index = dataGridView1.CurrentRow.Index;
    // take the value id = Worker.ID_Worker
    id = (int)dataGridView1.Rows[index].Cells[0].Value;
    accountBindingSource.Filter = "ID_Worker = " + id.ToString();
}

private void dataGridView1_CellEnter(object sender, DataGridViewCellEventArgs e)
{
    // create a filter that will output to dataGridView2 what you need
    int id;
    int index;

    index = dataGridView1.CurrentRow.Index;
    // take the value id = Worker.ID_Worker
    id = (int)dataGridView1.Rows[index].Cells[0].Value;
    accountBindingSource.Filter = "ID_Worker = " + id.ToString();
}

As you can see from the above code, the text of the event handlers is the same. Important here is the Filter field of the accountBindingSource object that was created by the system when connected to the Account table. This field is, in fact, a fragment of the condition in the SQL query. In SQL, the condition is determined by the keyword WHERE.

For example, if you specify in Filter

ID_Worker = 5

then this row will be converted to a fragment of the SQL-code

WHERE ID_Worker = 5

 

5.1.2. Test run. Text of the program

Now you can start the application and check its operation. When you change a row in the Worker table, the data of the Account table associated with that row is automatically displayed. As you know, the data is bound by the ID_Worker field.

At the moment, the text of the module Form1.cs is:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace Oblik01
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            // TODO: This line of code loads data into the 'accountDataSet.Account' table. You can move, or remove it, as needed.

            this.accountTableAdapter.Fill(this.accountDataSet.Account);

            // TODO: This line of code loads data into the 'accountDataSet.Worker' table. You can move, or remove it, as needed.
            this.workerTableAdapter.Fill(this.accountDataSet.Worker);
        }

        private void dataGridView1_Click(object sender, EventArgs e)
        {
            // create a filter that will output to dataGridView2 what you need
            int id;
            int index;

            index = dataGridView1.CurrentRow.Index;

            // take the value id = Worker.ID_Worker
            id = (int)dataGridView1.Rows[index].Cells[0].Value;
    accountBindingSource.Filter = "ID_Worker = " + id.ToString();
        }

        private void dataGridView1_CellEnter(object sender, DataGridViewCellEventArgs e)
        {
            // create a filter that will output to dataGridView2 what you need
            int id;
            int index;

            index = dataGridView1.CurrentRow.Index;

            // take the value id = Worker.ID_Worker
            id = (int)dataGridView1.Rows[index].Cells[0].Value;
            accountBindingSource.Filter = "ID_Worker = " + id.ToString();
        }
    }
}

 

5.1.3. Programming the command “Worker” => “Add…”

If the user selects the command “Add …” from the Worker menu, the FormAddWorker.cs window should be called. In this window, the data of the new worker is entered. The text of the Click event handler for selecting the menu command “Worker” => “Add …” has the following view:

C#. Windows Forms. The Click event of the menu command "Worker" => "Add..."

Figure 45. The Click event of the menu command “Worker” => “Add…”

The text of the event handler is as follows:

private void addToolStripMenuItem_Click(object sender, EventArgs e)
{
    FormAddWorker f = new FormAddWorker(); // create the form

    if (f.ShowDialog() == DialogResult.OK) //       show the form
    {
        // if OK, then add a worker
        string WName, WPosition, WSex;

        WName = f.textBox1.Text;
        WPosition = f.textBox2.Text;
        WSex = f.comboBox1.Items[f.comboBox1.SelectedIndex].ToString();

        // it works
        this.workerTableAdapter.Insert(WName, WPosition, WSex); // insert
        this.workerTableAdapter.Fill(this.accountDataSet.Worker); // display
    }
}

In the above code, the FormAddWorker window, which was designed in paragraph 4.1, is called. Then, the internal variables WName, WPosition, WSex are filled from this window. In the future, all work with changing the data in the Worker table will be performed with the workerTableAdapter object, which was created by the system when connecting to the database.

Inserting a string is done using the Insert() method of the workerTableAdapter object. This method is generated by the system programmatically when the Worker table is connected. The method programmatically generates parameters that correspond to the fields of the Worker table. This is very convenient.

The Fill() method fills changes to the database.

 

5.1.4. Programming the “Worker” => “Delete” command

When the Delete command is called from the Worker menu, the FormDelWorker confirmation form is called. The text of the Delete command’s event handler is as follows

private void deleteToolStripMenuItem_Click(object sender, EventArgs e)
{
    // Worker => Delete
    FormDelWorker f = new FormDelWorker(); // create the form
    int id_worker;
    string WName, WPosition, WSex;
    int index;

    // get the number of the current (selected) row in the dataGridView1
    index = dataGridView1.CurrentRow.Index;

    // fill the internal variables from the current row dataGridView1
    id_worker = Convert.ToInt32(dataGridView1[0, index].Value);
    WName = Convert.ToString(dataGridView1[1, index].Value);
    WPosition = Convert.ToString(dataGridView1[2, index].Value);
    WSex = Convert.ToString(dataGridView1[3, index].Value);

    // form the information line
    f.label2.Text = WName + " " + WPosition;

    if (f.ShowDialog() == DialogResult.OK)
    {
        workerTableAdapter.Delete(id_worker, WName, WPosition, WSex); // the Delete method
        this.workerTableAdapter.Fill(this.accountDataSet.Worker);
    }
}

In this handler, the Delete() method of the workerTableAdapter object is important. In this method, you need to specify the values of the fields of the row that is deleted.

 

5.1.5. Programming the “Worker” => “Edit…” command

The worker data is edited in the form FormEditWorker.cs (see paragraph 4.3) with the “Edit …” command of the Worker menu. The text of event handler of selecting the command

private void editToolStripMenuItem_Click(object sender, EventArgs e)
{
    // Worker => Edit...
    FormEditWorker f = new FormEditWorker(); // create the form
    int index;
    string WName, WPosition, WSex;
    int id_worker;

    if (dataGridView1.RowCount <= 1) return;

    // get the position of the selected row in dataGridView1
    index = dataGridView1.CurrentRow.Index;

    if (index == dataGridView1.RowCount - 1) return; //

    // get the row data
    id_worker = (int)dataGridView1.Rows[index].Cells[0].Value;
    WName = (string)dataGridView1.Rows[index].Cells[1].Value;
    WPosition = (string)dataGridView1.Rows[index].Cells[2].Value;
    WSex = (string)dataGridView1.Rows[index].Cells[3].Value;

    // fill in the form f
    f.textBox1.Text = WName;
    f.textBox2.Text = WPosition;

    if (WSex == "M") f.comboBox1.SelectedIndex = 0;
    else f.comboBox1.SelectedIndex = 1;

    if (f.ShowDialog() == DialogResult.OK) // call the FormEditWorker form
    {
        string nWName, nWPosition, nWSex;

        // get the new (changed) values from the form
        nWName = f.textBox1.Text;
        nWPosition = f.textBox2.Text;
        nWSex = f.comboBox1.Items[f.comboBox1.SelectedIndex].ToString();

        // make changes to the adapter
        this.workerTableAdapter.Update(nWName, nWPosition, nWSex, id_worker, WName, WPosition, WSex);
        this.workerTableAdapter.Fill(this.accountDataSet.Worker);
    }
}

The actual change in the table is performed by the Update() method of the workerTableAdapter data adapter. This method gets the old and new values of the row of the Worker table.

 

5.1.6. Programming the “Inventory” => “Add…” command

Based on the Worker => “Add …” command, the program code of the “Inventory” => “Add…” command is implemented. The text of the event handler is as follows:

private void addToolStripMenuItem1_Click(object sender, EventArgs e)
{
    // Inventory => Add...
    FormAddAccount f = new FormAddAccount(); // window

    if (f.ShowDialog() == DialogResult.OK)
    {
        int Id_Worker;
        int index;
        string ANum, ADate, AInvNum, AObjName;
        short ACount;
        double APrice;

        // get the values ID_Worker from table Worker
        index = dataGridView1.CurrentRow.Index; // position in dataGridView1
        Id_Worker = (int)dataGridView1.Rows[index].Cells[0].Value;

        // take the values of other fields from the FormAddAccount form
        ANum = f.textBox1.Text;
        ADate = f.textBox2.Text;
        AInvNum = f.textBox3.Text;
        AObjName = f.textBox4.Text;
        ACount = Convert.ToInt16(f.textBox5.Text);
        APrice = Convert.ToDouble(f.textBox6.Text);

        this.accountTableAdapter.Insert(Id_Worker, ANum, ADate, AInvNum, AObjName, ACount, APrice);
        this.accountTableAdapter.Fill(this.accountDataSet.Account);
    }
}

The Insert() method of the accountTableAdapter receives input values for the fields in the Account table.

 

5.1.7. Programming the “Inventory” => “Delete” command

The text of the event handler for the Delete command from the Inventory menu:

private void deleteToolStripMenuItem1_Click(object sender, EventArgs e)
{
    // Inventory => Delete
    FormDelAccount f = new FormDelAccount();

    int id_account, id_worker;
    string ANum, ADate, AInvNum, AObjName;
    short ACount;
    double APrice;
    int index;

    // get the index of the selected (current) row in the dataGridView2
    index = dataGridView2.CurrentRow.Index;

    // take the values of the fields of the row with the index number
    id_account = Convert.ToInt32(dataGridView2[0, index].Value);
    id_worker = Convert.ToInt32(dataGridView2[1, index].Value);
    ANum = Convert.ToString(dataGridView2[2, index].Value);
    ADate = Convert.ToString(dataGridView2[3, index].Value);
    AInvNum = Convert.ToString(dataGridView2[4, index].Value);
    AObjName = Convert.ToString(dataGridView2[5, index].Value);
    ACount = Convert.ToInt16(dataGridView2[6, index].Value);
    APrice = Convert.ToDouble(dataGridView2[7, index].Value);

    // form a information row in the FormDelAccount window
    f.label2.Text = ANum + " / " + ADate + " / " + AInvNum + " / " +
            AObjName + " / " + ACount + " / " + APrice;

    if (f.ShowDialog() == DialogResult.OK) // show the window
    {
        this.accountTableAdapter.Delete(id_account, id_worker,
            ANum, ADate, AInvNum, AObjName, ACount, APrice); // delete row
        this.accountTableAdapter.Fill(this.accountDataSet.Account); // commit changes
    }
}

 

5.1.8. Programming the “Inventory” => “Edit…” command

The text of the event handler is the following

private void editToolStripMenuItem1_Click(object sender, EventArgs e)
{
    // Inventory => Edit...
    FormEditAccount f = new FormEditAccount();
    int index;
    int id_account;
    int id_worker;
    string ANum, ADate, AInvNum, AObjName;
    short ACount;
    double APrice;

    if (dataGridView2.RowCount <= 1) return;

    // get the index of current row in dataGridView2
    index = dataGridView2.CurrentRow.Index;

    if (index == dataGridView2.RowCount-1) return; //

    // get the row data
    id_account = (int)dataGridView2.Rows[index].Cells[0].Value;
    id_worker = (int)dataGridView2.Rows[index].Cells[1].Value;
    ANum = (string)dataGridView2.Rows[index].Cells[2].Value;
    ADate = (string)dataGridView2.Rows[index].Cells[3].Value;
    AInvNum = (string)dataGridView2.Rows[index].Cells[4].Value;
    AObjName = (string)dataGridView2.Rows[index].Cells[5].Value;
    ACount = (short)dataGridView2.Rows[index].Cells[6].Value;
    APrice = (double)dataGridView2.Rows[index].Cells[7].Value;

    // filling data
    f.textBox1.Text = ANum;
    f.textBox2.Text = ADate;
    f.textBox3.Text = AInvNum;
    f.textBox4.Text = AObjName;
    f.textBox5.Text = Convert.ToString(ACount);
    f.textBox6.Text = Convert.ToString(APrice);

    // fill in the fields of FormEditAccount form
    if (f.ShowDialog() == DialogResult.OK) // call the form
    {
        // new row values
        string nANum, nADate, nAInvNum, nAObjName;
        short nACount;
        double nAPrice;

        // get a new values
        nANum = f.textBox1.Text;
        nADate = f.textBox2.Text;
        nAInvNum = f.textBox3.Text;
        nAObjName = f.textBox4.Text;
        nACount = Convert.ToInt16(f.textBox5.Text);
        nAPrice = Convert.ToDouble(f.textBox6.Text);

        // update data
        this.accountTableAdapter.Update(id_worker,nANum,nADate, nAInvNum, nAObjName,nACount,nAPrice,
        id_account,id_worker, ANum,ADate,AInvNum,AObjName,ACount,APrice);
        this.accountTableAdapter.Fill(this.accountDataSet.Account);
    }
}

 

5.1.9. Programming the filter by name in the “Worker” table. The TextChanged event of TextBox1 control

In order to provide convenience, the program can use the filter on the field WName of Worker table. To do this, the program uses the textBox1 control (Figure 46). To ensure quick text processing with textBox1, the entered text is processed in the TextChanged event (Figure 46).

C#. Windows Forms Application template. The textBox1 control. The TextChanged event

Figure 46. The textBox1 control. The TextChanged event

The textBox1_TextChanged() event handler corresponds to the TextChanged event. To filter the rows in the WName field of the Worker table, you need to fill the value of the Filter property in the workerBindingSource object. This property corresponds to the “… WHERE …” part of the SQL statement “SELECT … FROM … WHERE …”. In our case, we need to form a string

WName LIKE 'Text%'

where Text – text that is entered in the textBox1.Text string.

The text of the event handler is the following

// filter in textBox1
private void textBox1_TextChanged(object sender, EventArgs e)
{
    workerBindingSource.Filter = "WName LIKE '" + textBox1.Text + "%'";
}

After that, only entries that begin with the characters that are typed in textBox1.Text will be displayed in the Worker table. If nothing is entered in textBox1.Text, then all the records (rows) of the Worker table will be displayed.

 

5.1.10. Programming the “Exit” command

The text of the Click event handler of the “Exit” command

// Exit
private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
    Close();
}

 

5.2. Programming the Load event of the FormAddWorker form

In the Load event of the FormAddWorker form, you need to initialize the values of the form fields.

The text of the Load event handler for the FormAddWorker form (Worker -> Add …):

private void FormAddWorker_Load(object sender, EventArgs e)
{
    textBox1.Text = "";
    textBox2.Text = "";
    comboBox1.SelectedIndex = 1;
    textBox1.Focus(); // when you open a window, textBox1 gets focus
}

 

5.3. Programming the Load event of the FormEditWorker form

Text of the FormEditWorker event handler

private void FormEditWorker_Load(object sender, EventArgs e)
{
    textBox1.Focus();
}

 

5.4. Programming the Load event of the FormAddAccount form

The text of the event handler is as follows:

private void FormAddAccount_Load(object sender, EventArgs e)
{
    textBox1.Text = "";
    textBox2.Text = "";
    textBox3.Text = "";
    textBox4.Text = "";
    textBox5.Text = "";
    textBox6.Text = "";
    textBox1.Focus();
}

 

5.5. Programming the Load event of the FormEditAccount form

The text of the event handler is the following

private void FormEditAccount_Load(object sender, EventArgs e)
{
    textBox1.Focus();
}

 

6. Redirecting click event handlers on the shortcut buttons to menu commands

At this stage, you need to make the menu commands call by pressing the corresponding button on the main form. Appointment of buttons is as follows:

  • the “Add…” button calls the menu command “Worker-> Add …”;
  • the “Delete” button calls the command “Worker -> Delete”;
  • the “Edit…” button calls the command “Worker -> Edit…”;
  • the “Add record…” button calls the command “Inventory -> Add…”;
  • the “Delete record” button calls the command “Inventory-> Delete”;
  • the “Edit record…” button calls the command “Inventory -> Edit”.

C#. Windows Forms Application template. The menu command "Worker -> Add ..." and the "Add..." button

Figure 47. The menu command “Worker -> Add …” and the “Add…” button

No need to program the Click event handlers for the buttons again. The MS Visual Studio tools configure the appropriate event handlers, as shown in Figure 48. For the Click event of the “Add…” (button1) button, the event handler addToolStripMenuItem_Click() is assigned

C#. Windows Forms Application template. Assigning the event handling method addToolStripMenuItem_Click() for the "Add..." button

Figure 48. Assigning the event handling method addToolStripMenuItem_Click() for the “Add…” button

Also, the corresponding event handlers are assigned to other form buttons:

  • for the “Delete” command, the method deleteToolStripMenuItem_Click() is assigned;
  • for the “Edit…” command, the method editToolStripMenuItem_Click() is assigned;
  • for the “Add record…” command, the method addToolStripMenuItem1_Click() is assigned;
  • for the “Delete record” command, the method deleteToolStripMenuItem1_Click() is assigned;
  • for the “Edit record…” command, the method editToolStripMenuItem1_Click is assigned.

 

7. Run the program for execution. Conclusions

Now you can run the program to run.

This topic demonstrates the use of MS Visual Studio tools to manage the Microsoft Access database.

As it was shown, there is no need to program queries in SQL language programmatically. To do this, in the objects that the system creates, you need to properly configure the appropriate properties. Thus, a minimum of writing a program code is achieved. Since most of the work is done in dialog boxes, where you configure the appearance, communication, display.

The paper sets out in detail:

  • the organization of navigation on the tables on the principle of “primary”“secondary”. When the active record is changed in the primary table, the associated records of the secondary table are displayed accordingly;
  • use of objects of type TabelAdapter, BindingSource for convenient operation of data in tables;
  • convenient call of commands of change of the data in tables (INSERT, UPDATE, DELETE) by a call of corresponding methods which are generated by MS Visual Studio;
  • creating a calculated field and specify the accuracy of output of 2 decimal places;
  • programming a filter to display records in a table according to a given pattern;
  • use the MS Visual Studio window interface to easily customize the appearance (display) of database table fields.

 


Related topics