Staff.xaml.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. using System.Windows;
  7. using System.Windows.Controls;
  8. using System.Windows.Data;
  9. using System.Windows.Documents;
  10. using System.Windows.Input;
  11. using System.Windows.Media;
  12. using System.Windows.Media.Imaging;
  13. using System.Windows.Shapes;
  14. using System.Windows.Threading;
  15. using System.Data.SqlClient;
  16. using System.Data;
  17. namespace HotelCalifornia
  18. {
  19. /// <summary>
  20. /// Логика взаимодействия для Staff.xaml
  21. /// </summary>
  22. public partial class Staff : Window
  23. {
  24. public Staff()
  25. {
  26. InitializeComponent();
  27. //Таймер на обновление времени
  28. DispatcherTimer timer = new DispatcherTimer();
  29. timer.Tick += new EventHandler(Update_Timer_Tick);
  30. timer.Interval = new TimeSpan(0, 0, 1);
  31. timer.Start();
  32. }
  33. //Строка подключения
  34. SqlConnection con = new SqlConnection("Data Source=localhost;Initial Catalog=kursah;Integrated Security=True");
  35. //Вывод даты и время в textblock
  36. private void Update_Timer_Tick(object sender, EventArgs e)
  37. {
  38. timetxt.Text = DateTime.Now.ToString();
  39. }
  40. //Выход из приложения
  41. private void Close(object sender, RoutedEventArgs e)
  42. {
  43. Application.Current.Shutdown();
  44. }
  45. //Свернуть окно
  46. private void WindMin_Click(object sender, RoutedEventArgs e)
  47. {
  48. this.WindowState = WindowState.Minimized;
  49. }
  50. //Возврат к окну выбора функции
  51. private void Back(object sender, RoutedEventArgs e)
  52. {
  53. MainWindow mainWindow = new MainWindow();
  54. this.Close();
  55. mainWindow.Show();
  56. }
  57. //Выбор строки из БД
  58. private void datastaff_SelectionChanged(object sender, SelectionChangedEventArgs e)
  59. {
  60. try
  61. {
  62. DataGrid gd = (DataGrid)sender;
  63. DataRowView rowView = gd.SelectedItem as DataRowView;
  64. if (rowView != null)
  65. {
  66. idtxt.Text = rowView["ID_Administrator"].ToString();
  67. nametxt.Text = rowView["FirstName"].ToString();
  68. familiyatxt.Text = rowView["LastName"].ToString();
  69. otchestvotxt.Text = rowView["MiddleName"].ToString();
  70. logintxt.Text = rowView["Login"].ToString();
  71. passwordtxt.Password = rowView["Password"].ToString();
  72. rolecombo.Text = rowView["Name_Role"].ToString();
  73. }
  74. }
  75. catch (Exception ex)
  76. {
  77. MessageBox.Show("Возникла ошибка! " + ex.ToString(), "Ошибка", MessageBoxButton.OK, MessageBoxImage.Error);
  78. }
  79. }
  80. //Добавление администратора
  81. private void Add_Click(object sender, RoutedEventArgs e)
  82. {
  83. if (familiyatxt.Text == "" || nametxt.Text == "" || otchestvotxt.Text == "" || logintxt.Text == "" || passwordtxt.Password == "" || rolecombo.Text == "")
  84. {
  85. MessageBox.Show("Заполните все поля!", "Предупреждение", MessageBoxButton.OK, MessageBoxImage.Information);
  86. }
  87. else
  88. {
  89. try
  90. {
  91. con.Open();
  92. SqlCommand cmd = new SqlCommand("Select * from Administrator where Login ='" + logintxt.Text + "'", con);
  93. cmd.CommandType = CommandType.Text;
  94. SqlDataAdapter adapter = new SqlDataAdapter();
  95. adapter.SelectCommand = cmd;
  96. DataSet dataSet = new DataSet();
  97. adapter.Fill(dataSet);
  98. if (dataSet.Tables[0].Rows.Count > 0)
  99. {
  100. MessageBox.Show("Такой Администратор уже создан!", "Информация", MessageBoxButton.OK, MessageBoxImage.Information);
  101. con.Close();
  102. }
  103. else
  104. {
  105. string idrole = "";
  106. if (rolecombo.Text == "Администратор")
  107. idrole = "1";
  108. else
  109. idrole = "2";
  110. string sql = "INSERT INTO Administrator (LastName,FirstName,MiddleName,Login,Password,ID_Role) VALUES('" + familiyatxt.Text + "','" + nametxt.Text + "','" + otchestvotxt.Text + "','" + logintxt.Text + "','" + passwordtxt.Password + "', '" + idrole.ToString() + "')";
  111. SqlDataAdapter dataAdapter = new SqlDataAdapter(sql, con);
  112. dataAdapter.SelectCommand.ExecuteNonQuery();
  113. con.Close();
  114. showgrid();
  115. idtxt.Text = "";
  116. nametxt.Text = "";
  117. familiyatxt.Text = "";
  118. otchestvotxt.Text = "";
  119. logintxt.Text = "";
  120. passwordtxt.Password = "";
  121. rolecombo.Text = "";
  122. MessageBox.Show("Администратор был добавлен!", "Информация", MessageBoxButton.OK, MessageBoxImage.Information);
  123. }
  124. }
  125. catch (Exception ex)
  126. {
  127. con.Close();
  128. MessageBox.Show("Возникла ошибка! " + ex.ToString(), "Ошибка", MessageBoxButton.OK, MessageBoxImage.Error);
  129. }
  130. }
  131. }
  132. //Обновление администратора
  133. private void Update_Click(object sender, RoutedEventArgs e)
  134. {
  135. if (idtxt.Text == "")
  136. {
  137. MessageBox.Show("Поле не выбрано! Выберите нужное поле!", "Предупреждение", MessageBoxButton.OK, MessageBoxImage.Information);
  138. }
  139. else if (familiyatxt.Text == "" || nametxt.Text == "" || otchestvotxt.Text == "" || logintxt.Text == "" || passwordtxt.Password == "" || rolecombo.Text == "")
  140. {
  141. MessageBox.Show("Заполните все поля!", "Предупреждение", MessageBoxButton.OK, MessageBoxImage.Information);
  142. }
  143. else
  144. {
  145. try
  146. {
  147. con.Open();
  148. string idrole = "";
  149. if (rolecombo.Text == "Администратор")
  150. idrole = "1";
  151. else
  152. idrole = "2";
  153. string sql = "Update Administrator set FirstName ='" + nametxt.Text + "', LastName = '" + familiyatxt.Text + "', MiddleName = '" + otchestvotxt.Text + "', Login = '" + logintxt.Text + "', Password = '" + passwordtxt.Password + "', ID_Role = '"+idrole.ToString()+"' where ID_Administrator = '" + idtxt.Text + "'";
  154. SqlDataAdapter dataAdapter = new SqlDataAdapter(sql, con);
  155. dataAdapter.SelectCommand.ExecuteNonQuery();
  156. con.Close();
  157. idtxt.Text = "";
  158. nametxt.Text = "";
  159. familiyatxt.Text = "";
  160. otchestvotxt.Text = "";
  161. logintxt.Text = "";
  162. passwordtxt.Password = "";
  163. rolecombo.Text = "";
  164. showgrid();
  165. MessageBox.Show("Администратор был изменен!", "Информация", MessageBoxButton.OK, MessageBoxImage.Information);
  166. }
  167. catch (Exception ex)
  168. {
  169. con.Close();
  170. MessageBox.Show("Возникла ошибка! " + ex.ToString(), "Ошибка", MessageBoxButton.OK, MessageBoxImage.Error);
  171. }
  172. }
  173. }
  174. //Удаление администратора
  175. private void Delete_Click(object sender, RoutedEventArgs e)
  176. {
  177. if (idtxt.Text == "")
  178. {
  179. MessageBox.Show("Поле не выбрано! Выберите нужное поле!", "Предупреждение", MessageBoxButton.OK, MessageBoxImage.Information);
  180. }
  181. else
  182. {
  183. try
  184. {
  185. con.Open();
  186. string sql = "DELETE FROM Administrator WHERE ID_Administrator = '" + idtxt.Text + "'";
  187. SqlDataAdapter dataAdapter = new SqlDataAdapter(sql, con);
  188. dataAdapter.SelectCommand.ExecuteNonQuery();
  189. con.Close();
  190. idtxt.Text = "";
  191. nametxt.Text = "";
  192. familiyatxt.Text = "";
  193. otchestvotxt.Text = "";
  194. logintxt.Text = "";
  195. passwordtxt.Password = "";
  196. rolecombo.Text = "";
  197. showgrid();
  198. MessageBox.Show("Администратор удален!", "Информация", MessageBoxButton.OK, MessageBoxImage.Information);
  199. }
  200. catch (Exception ex)
  201. {
  202. con.Close();
  203. MessageBox.Show("Возникла ошибка! " + ex.ToString(), "Ошибка", MessageBoxButton.OK, MessageBoxImage.Error);
  204. }
  205. }
  206. }
  207. //Ограничение для ввода текста
  208. #region Ограничение
  209. private void nametxt_TextChanged(object sender, TextChangedEventArgs e)
  210. {
  211. if (sender is TextBox textBox)
  212. {
  213. textBox.Text = new string
  214. (textBox.Text.Where(ch => (ch >= 'А' && ch <= 'Я') || (ch >= 'а' && ch <= 'я')).ToArray());
  215. }
  216. }
  217. private void familiyatxt_TextChanged(object sender, TextChangedEventArgs e)
  218. {
  219. if (sender is TextBox textBox)
  220. {
  221. textBox.Text = new string
  222. (textBox.Text.Where(ch => (ch >= 'А' && ch <= 'Я') || (ch >= 'а' && ch <= 'я')).ToArray());
  223. }
  224. }
  225. private void otchestvotxt_TextChanged(object sender, TextChangedEventArgs e)
  226. {
  227. if (sender is TextBox textBox)
  228. {
  229. textBox.Text = new string
  230. (textBox.Text.Where(ch => (ch >= 'А' && ch <= 'Я') || (ch >= 'а' && ch <= 'я')).ToArray());
  231. }
  232. }
  233. private void logintxt_TextChanged(object sender, TextChangedEventArgs e)
  234. {
  235. if (sender is TextBox textBox)
  236. {
  237. textBox.Text = new string
  238. (textBox.Text.Where(ch => (ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z') || (ch >= '0' && ch <= '9')).ToArray());
  239. }
  240. }
  241. private void passwordtxt_PasswordChanged(object sender, RoutedEventArgs e)
  242. {
  243. if (sender is TextBox textBox)
  244. {
  245. textBox.Text = new string
  246. (textBox.Text.Where(ch => (ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z') || (ch >= '0' && ch <= '9')).ToArray());
  247. }
  248. }
  249. #endregion
  250. //Фомировка данных из БД
  251. void showgrid()
  252. {
  253. try
  254. {
  255. con.Open();
  256. string sql = "SELECT ID_Administrator,LastName, FirstName, MiddleName, Login, Password, [Name_Role] From Administrator inner join Role on Administrator.ID_Role = Role.ID_Role";
  257. SqlDataAdapter dataAdapter = new SqlDataAdapter(sql, con);
  258. DataTable data = new DataTable("Administrator");
  259. dataAdapter.Fill(data);
  260. datastaff.ItemsSource = data.DefaultView;
  261. dataAdapter.Update(data);
  262. con.Close();
  263. datastaff.Columns[0].Header = "ID";
  264. datastaff.Columns[1].Header = "Фамилия";
  265. datastaff.Columns[2].Header = "Имя";
  266. datastaff.Columns[3].Header = "Отчество";
  267. datastaff.Columns[4].Header = "Логин";
  268. datastaff.Columns[6].Header = "Роль";
  269. datastaff.Columns[5].Visibility = Visibility.Collapsed;
  270. datastaff.Columns[0].Visibility = Visibility.Collapsed;
  271. }
  272. catch (Exception ex)
  273. {
  274. con.Close();
  275. MessageBox.Show("Возникла ошибка! " + ex.ToString(), "Ошибка", MessageBoxButton.OK, MessageBoxImage.Error);
  276. }
  277. }
  278. void fillrolecombo()
  279. {
  280. try
  281. {
  282. rolecombo.Items.Clear();
  283. con.Open();
  284. SqlCommand sql = con.CreateCommand();
  285. sql.CommandType = CommandType.Text;
  286. sql.CommandText = "Select Name_Role from Role";
  287. sql.ExecuteNonQuery();
  288. DataTable dt = new DataTable();
  289. SqlDataAdapter da = new SqlDataAdapter(sql);
  290. da.Fill(dt);
  291. foreach (DataRow dr in dt.Rows)
  292. {
  293. rolecombo.Items.Add(dr["Name_Role"].ToString());
  294. }
  295. con.Close();
  296. }
  297. catch (Exception ex)
  298. {
  299. con.Close();
  300. MessageBox.Show("Возникла ошибка! " + ex.ToString(), "Ошибка", MessageBoxButton.OK, MessageBoxImage.Error);
  301. }
  302. }
  303. //Обновление
  304. private void Refresh_Click(object sender, RoutedEventArgs e)
  305. {
  306. showgrid();
  307. idtxt.Text = "";
  308. nametxt.Text = "";
  309. familiyatxt.Text = "";
  310. otchestvotxt.Text = "";
  311. logintxt.Text = "";
  312. passwordtxt.Password = "";
  313. rolecombo.Text = "";
  314. }
  315. //Перетаскивание окна
  316. private void Grid_MouseDown(object sender, MouseButtonEventArgs e)
  317. {
  318. try
  319. {
  320. DragMove();
  321. }
  322. catch
  323. {
  324. }
  325. }
  326. //Запуск в самом начале
  327. private void Window_Loaded(object sender, RoutedEventArgs e)
  328. {
  329. showgrid();
  330. fillrolecombo();
  331. }
  332. }
  333. }