1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
| using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Configuration;
using Microsoft.Reporting.WinForms;
namespace NewApp
{
public partial class MainForm : Form
{
DataSet ds;
SqlDataAdapter sda;
String UserName;
bool Admin = false;
int id_filter;
string conn_str = ConfigurationManager.ConnectionStrings["ConnectDB"].ConnectionString;//Properties.Settings.Default.str_Connection; //@"Data Source=.\SQLEXPRESS;Initial Catalog=DO;Integrated Security=True";
public MainForm()
{
InitializeComponent();
}
private void MainForm_Load(object sender, EventArgs e)
{
//Берем полное имя пользователя: домен\имя_пользователя
UserName = (Environment.UserDomainName + "\\" + Environment.UserName).ToLower();
using (SqlConnection connection = new SqlConnection(conn_str))
{
connection.Open();
//Проверка пользователя админ он или нет
SqlCommand command = new SqlCommand("SELECT User_admin from D.Преподаватель where user_login = @login",connection);
command.Parameters.AddWithValue("@login", UserName);
object value = command.ExecuteScalar();
connection.Close();
if (value != null)
{
Admin = Convert.ToBoolean(value.ToString());
}
if (Admin==false)
{
//удаляем вкладки
tabs_Menu.TabPages.Remove(tab_spravochniki);
tabs_Menu.TabPages.Remove(tab_reports);
//Прячем меню
Menu_Derictories.Visible = false;
//Узнаем id_Ползователя
connection.Open();
SqlCommand commands = new SqlCommand("SELECT КодПреподавателя from D.Преподаватель where user_login = @login", connection);
commands.Parameters.AddWithValue("@login", UserName);
value = commands.ExecuteScalar();
connection.Close();
id_filter = Convert.ToInt32(value.ToString());
}
}
Osnovy_courses();
this.reportViewer1.RefreshReport();
}
private void btn_coursDell_Click(object sender, EventArgs e)
{
DataGrid_Del_select(dgv_courses);
}
private void btn_coursAdd_Click(object sender, EventArgs e)
{
if (cb_teachers.SelectedIndex > -1 && cb_categories.SelectedIndex > -1 && txt_nameCourses.Text != "")
{
DataRow row = ds.Tables[0].NewRow();
row["Наименование курса"] = txt_nameCourses.Text;
row["КодКатегории"] = (int)cb_categories.SelectedValue;
row["Категория"] = cb_categories.Text.ToString();
row["Код_преподавателя"] = (int)cb_teachers.SelectedValue;
row["ФИО"] = cb_teachers.Text.ToString();
int res;
bool isInt = Int32.TryParse(txt_countThems.Text, out res);
row["Кол-во тем"] = res;
row["Примечания"] = txt_notes.Text;
row["Сайт"] = chb_AddsSite.Checked;
row["Guid"] = Guid.NewGuid(); //уникальная строка для поиска после добоавления, но еще не сохраненой записив бд
ds.Tables[0].Rows.Add(row);
//очищаем поля для удобства
ochistka_control(tab_courses);
}
}
private void btn_coursEdit_Click(object sender, EventArgs e)
{
if (cb_teachers.SelectedIndex > -1 && cb_categories.SelectedIndex > -1 && txt_nameCourses.Text != "")
foreach (DataGridViewRow row in dgv_courses.SelectedRows)
{
if (dgv_courses.CurrentRow.Selected == true)
{
DialogResult result = MessageBox.Show("Изменить выбранную строку? ", "Внимание", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (result == DialogResult.No) return;
else
{
DataRow dr;
//Поиск строки в таблице по коду, проверка по уже существуещий записе и новой записе
if (dgv_courses.SelectedRows[0].Cells["КодКурса"].Value.ToString()!="")
dr = ds.Tables[0].Select("КодКурса=" + dgv_courses.SelectedRows[0].Cells["КодКурса"].Value.ToString()).FirstOrDefault();
else
dr = ds.Tables[0].Select("Guid='" + dgv_courses.SelectedRows[0].Cells["Guid"].Value.ToString()+"'").FirstOrDefault();
if (dr != null)
{
dr["Наименование курса"] = txt_nameCourses.Text;
dr["КодКатегории"] = (int)cb_categories.SelectedValue;
dr["Категория"] = cb_categories.Text.ToString();
dr["Код_преподавателя"] = (int)cb_teachers.SelectedValue;
dr["ФИО"] = cb_teachers.Text.ToString();
int res;
bool isInt = Int32.TryParse(txt_countThems.Text, out res);
dr["Кол-во тем"] = res;
dr["Примечания"] = txt_notes.Text;
dr["Сайт"] = chb_AddsSite.Checked;
}
}
}
else MessageBox.Show("Не выбрано не одной строки", "Внимание", MessageBoxButtons.OK);
}
}
private void dgv_courses_MouseDoubleClick(object sender, MouseEventArgs e)
{
txt_nameCourses.Text = dgv_courses.SelectedRows[0].Cells["Наименование курса"].Value.ToString();
txt_countThems.Text = dgv_courses.SelectedRows[0].Cells["Кол-во тем"].Value.ToString();
txt_notes.Text = dgv_courses.SelectedRows[0].Cells["Примечания"].Value.ToString();
cb_teachers.SelectedValue = dgv_courses.SelectedRows[0].Cells["Код_преподавателя"].Value.ToString();
cb_categories.SelectedValue = dgv_courses.SelectedRows[0].Cells["КодКатегории"].Value.ToString();
chb_AddsSite.Checked = Convert.ToBoolean(dgv_courses.SelectedRows[0].Cells["Сайт"].Value.ToString());
}
//Вводить можно только цифры в количество тем
private void txt_countThems_KeyPress(object sender, KeyPressEventArgs e)
{
tolko_number(e);
}
private void btn_coursSave_Click(object sender, EventArgs e)
{
try
{
using (SqlConnection connection = new SqlConnection(conn_str))
{
connection.Open();
//Команды для добавления строк
SqlCommand command = new SqlCommand(
" INSERT INTO D.Курс " +
" (НаименованиеКурса, КодКатегории, Код_преподавателя, КоличествоТем, Сайт, Примечания) " +
" VALUES(@name, @kod_categories, @kod_teach, @count_tem, @site, @note);"
, connection);
command.Parameters.Add("@name", SqlDbType.NVarChar, 100, "Наименование курса");
command.Parameters.Add("@kod_categories", SqlDbType.Int, 4, "КодКатегории");
command.Parameters.Add("@kod_teach", SqlDbType.Int, 4, "Код_преподавателя");
command.Parameters.Add("@count_tem", SqlDbType.Int, 4, "Кол-во тем");
command.Parameters.Add("@site", SqlDbType.Bit, 1, "Сайт");
command.Parameters.Add("@note", SqlDbType.NText, 250, "Примечания");
sda.InsertCommand = command;
//Команды для обновления строк
command = new SqlCommand(
" UPDATE D.Курс " +
" SET НаименованиеКурса = @name, КодКатегории = @kod_categories, Код_преподавателя = @kod_teach, " +
" КоличествоТем = @count_tem, Сайт = @site, Примечания = @note" +
" WHERE D.Курс.КодКурса = @kod_cours;"
, connection);
command.Parameters.Add("@name", SqlDbType.NVarChar, 100, "Наименование курса");
command.Parameters.Add("@kod_categories", SqlDbType.Int, 4, "КодКатегории");
command.Parameters.Add("@kod_teach", SqlDbType.Int, 4, "Код_преподавателя");
command.Parameters.Add("@count_tem", SqlDbType.Int, 4, "Кол-во тем");
command.Parameters.Add("@site", SqlDbType.Bit, 1, "Сайт");
command.Parameters.Add("@note", SqlDbType.NText, 250, "Примечания");
command.Parameters.Add("@kod_cours", SqlDbType.Int, 4, "КодКурса");
sda.UpdateCommand = command;
//Команды для удаления строк
command = new SqlCommand(
" DELETE FROM D.Курс WHERE D.Курс.КодКурса = @kod_cours; "
, connection);
command.Parameters.Add("@kod_cours", SqlDbType.Int, 4, "КодКурса");
sda.DeleteCommand = command;
//Принемаем все изменения
sda.Update(ds);
connection.Close();
MessageBox.Show("Все изменения сохранены!", "Внимание", MessageBoxButtons.OK, MessageBoxIcon.Information);
Osnovy_courses();
}
}
catch
{
MessageBox.Show("Что-то пошло не так, обратитесь к администратору!", "Предупреждение!", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
private void btn_coursPoisk_Click(object sender, EventArgs e)
{
var f = new List<string>();
if (txt_nameCourses.Text !="")
f.Add(String.Format("[Наименование курса] like '%{0}%'", txt_nameCourses.Text));
if(txt_countThems.Text !="")
f.Add(String.Format("[Кол-во тем] = '{0}'", txt_countThems.Text));
if (txt_notes.Text != "")
f.Add(String.Format("[Примечания] like '%{0}%'", txt_notes.Text));
if (cb_teachers.SelectedIndex > -1)
f.Add(String.Format("[Код_преподавателя] = '{0}'", (int)cb_teachers.SelectedValue));
if (cb_categories.SelectedIndex > -1)
f.Add(String.Format("[КодКатегории] = '{0}'", (int)cb_categories.SelectedValue));
f.Add(String.Format("[Сайт] = '{0}'", chb_AddsSite.Checked));
(dgv_courses.DataSource as DataTable).DefaultView.RowFilter = string.Join(" AND ", f);
}
private void btn_coursClear_Click(object sender, EventArgs e)
{
(dgv_courses.DataSource as DataTable).DefaultView.RowFilter =
String.Format("1 = 1");
ochistka_control(tab_courses);
}
private void Osnovy_courses()
{
dgv_courses.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
dgv_courses.AllowUserToAddRows = false;
using (SqlConnection con = new SqlConnection(conn_str))
{
con.Open();
sda = new SqlDataAdapter();
string where="";
if (Admin == false)
where = "WHERE D.Преподаватель.User_login = @login ;";
SqlCommand command = new SqlCommand();
command = new SqlCommand("SELECT '' as Guid, D.Курс.КодКурса, D.Курс.НаименованиеКурса as 'Наименование курса', D.Преподаватель.Фамилия + ' ' + D.Преподаватель.Имя + ' ' + D.Преподаватель.Отчество AS ФИО " +
", D.Курс.КодКатегории, D.Курс.Код_преподавателя, D.Курс.КоличествоТем as 'Кол-во тем', D.Курс.Сайт, D.Курс.Примечания, " +
" D.Категории.НаименованиеКатегории as 'Категория' "+
" FROM D.Курс" +
" INNER JOIN D.Преподаватель ON D.Курс.Код_преподавателя = D.Преподаватель.КодПреподавателя " +
" INNER JOIN D.Категории ON D.Курс.КодКатегории = D.Категории.КодКатегории " +
where , con);
if(Admin == false)
command.Parameters.AddWithValue("@login", UserName);
sda.SelectCommand = command;
ds = new DataSet();
sda.Fill(ds);
dgv_courses.DataSource = ds.Tables[0];
//прячем лишнее
dgv_courses.Columns["Guid"].Visible = false;
dgv_courses.Columns["КодКурса"].ReadOnly = true;
dgv_courses.Columns["КодКурса"].Visible = false;
dgv_courses.Columns["КодКатегории"].Visible = false;
dgv_courses.Columns["Код_преподавателя"].Visible = false;
//Заполняем раскрывающийся список
if(Admin==false)
{
set_ComboBox(cb_teachers, "Список_Преподавателей", "ФИО_полностью", "КодПреподавателя", con, id_filter);
//Запрещаем редактировать раскрывающйся список
// MessageBox.Show(id_filter.ToString());
cb_teachers.SelectedValue = id_filter.ToString();
cb_teachers.Enabled = false;
}
else set_ComboBox(cb_teachers, "Список_Преподавателей", "ФИО_полностью", "КодПреподавателя", con);
set_ComboBox(cb_categories, "Список_Категорий", "НаименованиеКатегории", "КодКатегории", con);
//очищаем поля для удобства
ochistka_control(tab_courses);
con.Close();
}
}
private void btn_report_courses_1_Click(object sender, EventArgs e)
{
report("Отчет_Курсы", "Report_Courses_1.rdlc");
}
private void btn_report_courses_2_Click(object sender, EventArgs e)
{
report("Отчет_Курсы", "Report_Courses_2.rdlc");
}
private void btn_report_courses_3_Click(object sender, EventArgs e)
{
report("Отчет_Расписание", "Report_Courses_3.rdlc");
}
private void btn_report_courses_4_Click(object sender, EventArgs e)
{
report("Отчет_Курсы", "Report_Courses_4.rdlc");
}
/// <summary>
/// Функция проверяет вводимые символы на число и разрешает удаления
/// </summary>
/// <param name="e">KeyPressEventArgs - код клавиши</param>
private void tolko_number(KeyPressEventArgs e)
{
char number = e.KeyChar;
if (!Char.IsDigit(number) && number != 8) // цифры и клавиша BackSpace
{
e.Handled = true;
}
}
/// <summary>
/// Очищает TextBox, ComboBox, CheckBox в контейнере
/// </summary>
/// <param name="contr">Передать контейнер в котором расположены контролы</param>
private void ochistka_control(Control contr)
{
//Перебор всех контролов
foreach (Control c in contr.Controls)
{
CheckBox chek = c as CheckBox;
if (chek != null)
if(chek.Enabled == true)
chek.Checked = false;
ComboBox cb = c as ComboBox;
if (cb != null)
if (cb.Enabled == true)
cb.SelectedIndex = -1;
TextBox txt = c as TextBox;
if (txt != null)
if (txt.Enabled == true)
txt.Text = "";
}
}
/// <summary>
/// Удаляет выделеные строки в DataGridView
/// </summary>
/// <param name="dgv">DataGridView - с кот. надо удалить строки</param>
private void DataGrid_Del_select(DataGridView dgv)
{
foreach (DataGridViewRow row in dgv.SelectedRows)
{
if (dgv.CurrentRow.Selected == true)
{
DialogResult result = MessageBox.Show("Удалить выбранную строку? ", "Внимание", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (result == DialogResult.No) return;
else dgv.Rows.Remove(row);
}
else MessageBox.Show("Не выбрано не одной строки", "Внимание", MessageBoxButtons.OK);
}
}
/// <summary>
/// Вызывает хранимую процедуру, и заполняет раскрывающися список,
/// Возможно передовать id записи для возвращения только одного значения
/// </summary>
/// <param name="cb">ComboBox - который надо заполнить</param>
/// <param name="proc">Хранимая процедура</param>
/// <param name="display">Название колонки для отображения</param>
/// <param name="value">Название колонки для значений</param>
/// <param name="con">Открытая сесия с БД</param>
/// <param name="id">Не обязательный пораметр, филтр по id</param>
private void set_ComboBox(ComboBox cb, string proc, string display, string value, SqlConnection con, int id = -1)
{
SqlDataAdapter sda_cb = new SqlDataAdapter();
DataSet ds_cb = new DataSet();
SqlCommand command = new SqlCommand(proc, con);
command.CommandType = System.Data.CommandType.StoredProcedure;
if (id > -1)
{
SqlParameter param = new SqlParameter("@id", id);
command.Parameters.Add(param);
}
sda_cb.SelectCommand = command;
sda_cb.Fill(ds_cb);
cb.DataSource = ds_cb.Tables[0];
cb.DisplayMember = display;
cb.ValueMember = value;
}
/// <summary>
/// Процедура прикрепляет готовый отчет к форме отображения
/// </summary>
/// <param name="sql">название хранимой процедуры</param>
/// <param name="name_report">имя файла отчетов</param>
private void report(string sql, string name_report)
{
using (SqlConnection sqlConn = new SqlConnection(conn_str))
using (SqlDataAdapter da = new SqlDataAdapter(sql, conn_str))
{
DataSet ds = new DataSet();
da.Fill(ds);
DataTable dt = ds.Tables[0];
this.reportViewer1.Reset();
this.reportViewer1.ProcessingMode = ProcessingMode.Local;
this.reportViewer1.LocalReport.ReportPath = AppDomain.CurrentDomain.BaseDirectory + name_report;
ReportDataSource reportDataSource = new ReportDataSource();
// Must match the DataSet in the RDLC
reportDataSource.Name = "DataSet1";
reportDataSource.Value = ds.Tables[0];
this.reportViewer1.LocalReport.DataSources.Add(reportDataSource);
this.reportViewer1.RefreshReport();
}
}
#endregion
private void button1_Click(object sender, EventArgs e)
{
report("Список_Курсов", "Report1.rdlc");
}
} |