Skip to content

Commit 844a995

Browse files
committed
Условие задачи:
УСЛОВИЕ ЗАДАЧИ: Создайте базу данных Продажи (в качестве формата базы данных можно использовать Microsoft Access). Создайте внутри базы данных три таблицы: a. Таблица Покупатели. Столбцы: идентификатор, имя, фамилия; b. Таблица Продавцы. Столбцы: идентификатор, имя, фамилия; c. Таблица Продажи. Столбцы: идентификатор сделки, идентификатор покупателя, идентификатор продавца, сумма сделки, дата сделки. Наполните таблицы данными, задайте правила ссылочной целостности. Реализуйте WinForms приложение, позволяющее пользователю выбрать название таблицы из базы данных sample.mdb (например, с помощью выпадающего списка), в результате выбора таблицы приложение должно отображать содержимое данной таблицы на форму.
1 parent 7092e30 commit 844a995

File tree

14 files changed

+1093
-0
lines changed

14 files changed

+1093
-0
lines changed
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
2+
Microsoft Visual Studio Solution File, Format Version 12.00
3+
# Visual Studio 14
4+
VisualStudioVersion = 14.0.23107.0
5+
MinimumVisualStudioVersion = 10.0.40219.1
6+
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Hometask-1", "Hometask-1\Hometask-1.csproj", "{B72C387A-7997-4914-BE31-F74951F1F46B}"
7+
EndProject
8+
Global
9+
GlobalSection(SolutionConfigurationPlatforms) = preSolution
10+
Debug|Any CPU = Debug|Any CPU
11+
Release|Any CPU = Release|Any CPU
12+
EndGlobalSection
13+
GlobalSection(ProjectConfigurationPlatforms) = postSolution
14+
{B72C387A-7997-4914-BE31-F74951F1F46B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
15+
{B72C387A-7997-4914-BE31-F74951F1F46B}.Debug|Any CPU.Build.0 = Debug|Any CPU
16+
{B72C387A-7997-4914-BE31-F74951F1F46B}.Release|Any CPU.ActiveCfg = Release|Any CPU
17+
{B72C387A-7997-4914-BE31-F74951F1F46B}.Release|Any CPU.Build.0 = Release|Any CPU
18+
EndGlobalSection
19+
GlobalSection(SolutionProperties) = preSolution
20+
HideSolutionNode = FALSE
21+
EndGlobalSection
22+
EndGlobal
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
<?xml version="1.0" encoding="utf-8" ?>
2+
<configuration>
3+
<startup>
4+
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
5+
</startup>
6+
</configuration>

Homeworks/ShagSchool/ADO.NET/Lesson-1/Hometasks/Hometask-1/Hometask-1/FormMain.Designer.cs

Lines changed: 105 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.
Lines changed: 232 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,232 @@
1+
using System;
2+
using System.Collections.Generic;
3+
using System.ComponentModel;
4+
using System.Data;
5+
using System.Data.SqlClient;
6+
using System.Drawing;
7+
using System.Linq;
8+
using System.Text;
9+
using System.Threading.Tasks;
10+
using System.Windows.Forms;
11+
12+
namespace Hometask_1
13+
{
14+
public partial class FormMain: Form
15+
{
16+
//ПОЛЯ КЛАССА
17+
//+-------------------------------------------------------------------+
18+
19+
SqlConnection dbConnection = null;
20+
SqlConnectionStringBuilder sqlStringBuilder = null;
21+
SqlCommand command = null;
22+
SqlDataReader reader = null;
23+
24+
25+
26+
//КОНСТРУКТОР КЛАССА
27+
//+-------------------------------------------------------------------+
28+
29+
/// <summary>
30+
/// Создание окна и его элементов
31+
/// </summary>
32+
public FormMain()
33+
{
34+
try
35+
{
36+
this.DbInitialization();
37+
this.InitializeComponent();
38+
this.EventSubscriptionInitialization();
39+
}
40+
catch (Exception ex)
41+
{
42+
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK,
43+
MessageBoxIcon.Exclamation);
44+
}
45+
}
46+
47+
48+
49+
//МЕТОДЫ КЛАССА
50+
//+-------------------------------------------------------------------+
51+
52+
/// <summary>
53+
/// Создание подключения к базе данных "SALES"
54+
/// </summary>
55+
private void DbInitialization()
56+
{
57+
this.sqlStringBuilder = new SqlConnectionStringBuilder();
58+
this.sqlStringBuilder.DataSource = "TAMARRA";
59+
this.sqlStringBuilder.IntegratedSecurity = true;
60+
this.sqlStringBuilder.InitialCatalog = "SALES";
61+
62+
this.dbConnection = new SqlConnection();
63+
this.dbConnection.ConnectionString = this.sqlStringBuilder.ConnectionString;
64+
this.dbConnection.Open();
65+
}
66+
67+
/// <summary>
68+
/// Закрытие подключеия к базе данных "SALES"
69+
/// </summary>
70+
private void DbDrop(Object sender, FormClosedEventArgs e)
71+
{
72+
if (this.dbConnection != null)
73+
{
74+
this.dbConnection.Close();
75+
this.dbConnection = null;
76+
}
77+
}
78+
79+
/// <summary>
80+
/// Подкиска обработчиков событий на события
81+
/// </summary>
82+
private void EventSubscriptionInitialization()
83+
{
84+
this.comboBoxTable.DropDown += new EventHandler(this.SetComboBoxItems);
85+
this.comboBoxTable.SelectedIndexChanged += new EventHandler(this.SetTextBoxText);
86+
this.FormClosed += new FormClosedEventHandler(DbDrop);
87+
}
88+
89+
/// <summary>
90+
/// Заполнение строк выпадающего меню элемента "ComboBox"
91+
/// </summary>
92+
private void SetComboBoxItems(Object sender, EventArgs e)
93+
{
94+
try
95+
{
96+
if(this.comboBoxTable.Items != null)
97+
{
98+
this.comboBoxTable.Items.Clear();
99+
}
100+
this.command = new SqlCommand("SELECT [TABLE_NAME] " +
101+
"FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = 'BASE TABLE' " +
102+
"AND TABLE_CATALOG = 'SALES'", dbConnection);
103+
reader = this.command.ExecuteReader();
104+
105+
List<Object> items = new List<Object>();
106+
while (this.reader.Read())
107+
{
108+
items.Add(reader["TABLE_NAME"]);
109+
}
110+
this.comboBoxTable.Items.AddRange(items.ToArray());
111+
}
112+
finally
113+
{
114+
if(this.reader != null)
115+
{
116+
this.reader.Close();
117+
this.reader = null;
118+
}
119+
}
120+
}
121+
122+
/// <summary>
123+
/// Заполнение текстом элемента "TextBox"
124+
/// </summary>
125+
private void SetTextBoxText(Object sender, EventArgs e)
126+
{
127+
try
128+
{
129+
if (this.textBoxTableData.Text != null)
130+
{
131+
this.textBoxTableData.Text = null;
132+
}
133+
134+
String sqlQuery = null;
135+
if ((string)this.comboBoxTable.SelectedItem == "Buyers" ||
136+
(string)this.comboBoxTable.SelectedItem == "Sellers")
137+
{
138+
sqlQuery = String.Format("SELECT * FROM [{0}]",
139+
(string)this.comboBoxTable.SelectedItem);
140+
}
141+
else
142+
{
143+
sqlQuery = String.Format(
144+
"SELECT[Sellers].[LastName] AS[Seller Last Name], " +
145+
"[Sellers].[FirstName] AS[Seller First Name], " +
146+
"[Buyers].[LastName] AS[Buyer Last Name], " +
147+
"[Buyers].[FirstName] AS[Buyer First Name], " +
148+
"[Sales].[Total] AS[Total Sales] " +
149+
"FROM[Sellers] INNER JOIN([Buyers] " +
150+
"INNER JOIN[Sales] ON[Buyers].[BuyerId] = " +
151+
"[Sales].[BuyerId]) ON [Sellers].SellerId = " +
152+
"[Sales].[SellerId] ORDER BY[Total Sales] DESC ");
153+
}
154+
155+
this.command = new SqlCommand(sqlQuery, this.dbConnection);
156+
reader = this.command.ExecuteReader();
157+
158+
StringBuilder tableColumnNames = new StringBuilder();
159+
tableColumnNames = GetTableColumsNames();
160+
StringBuilder tableRows = new StringBuilder();
161+
tableRows = GetTableRows();
162+
163+
this.textBoxTableData.AppendText(tableColumnNames.ToString() +
164+
tableRows.ToString());
165+
this.textBoxTableData.ScrollBars = ScrollBars.Both;
166+
}
167+
finally
168+
{
169+
if (this.reader != null)
170+
{
171+
this.reader.Close();
172+
this.reader = null;
173+
}
174+
}
175+
}
176+
177+
/// <summary>
178+
/// Возвращает имена столбцов таблицы
179+
/// </summary>
180+
/// <returns>имена столбцов таблицы</returns>
181+
private StringBuilder GetTableColumsNames()
182+
{
183+
StringBuilder tableColumnNames = new StringBuilder();
184+
185+
//Вставка в текст заголовков столбцов
186+
for (int i = 0; i < reader.FieldCount; i++)
187+
{
188+
if (i == 0)
189+
{
190+
tableColumnNames.AppendFormat("{0, -20}",
191+
reader.GetName(i));
192+
}
193+
else
194+
{
195+
tableColumnNames.AppendFormat("{0, -20}",
196+
reader.GetName(i));
197+
}
198+
}
199+
tableColumnNames.AppendLine(Environment.NewLine);
200+
201+
return tableColumnNames;
202+
}
203+
204+
/// <summary>
205+
/// Возвращает данные содержащиеся в таблице
206+
/// </summary>
207+
/// <returns>данные таблицы</returns>
208+
private StringBuilder GetTableRows()
209+
{
210+
StringBuilder tableRows = new StringBuilder();
211+
212+
//Вставка в текст данных таблицы
213+
while (this.reader.Read() != false)
214+
{
215+
for (int i = 0; i < this.reader.FieldCount; i++)
216+
{
217+
if (i == 0)
218+
{
219+
tableRows.AppendFormat("{0,-20}", reader[i]);
220+
}
221+
else
222+
{
223+
tableRows.AppendFormat("{0,-20}", reader[i]);
224+
}
225+
}
226+
tableRows.AppendLine();
227+
}
228+
229+
return tableRows;
230+
}
231+
}
232+
}

0 commit comments

Comments
 (0)