using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Shapes; using System.Windows.Threading; using System.Data; using System.Data.SqlClient; namespace HotelCalifornia { /// /// Логика взаимодействия для Room.xaml /// public partial class Room : Window { public Room() { InitializeComponent(); //Таймер на обновление времени DispatcherTimer timer = new DispatcherTimer(); timer.Tick += new EventHandler(Update_Timer_Tick); timer.Interval = new TimeSpan(0, 0, 1); timer.Start(); } //Строка подключения SqlConnection con = new SqlConnection("Data Source=localhost;Initial Catalog=kursah;Integrated Security=True"); //Значение статуса string status = ""; //Вывод даты и время в textblock private void Update_Timer_Tick(object sender, EventArgs e) { timetxt.Text = DateTime.Now.ToString(); } //Перетаскивание окна private void Grid_MouseDown(object sender, MouseButtonEventArgs e) { DragMove(); } //Возврат к окну выбора функции private void Back(object sender, RoutedEventArgs e) { Variant variant = new Variant(); variant.idadmintxt.Text = idadmintxt.Text; this.Close(); variant.Show(); } //Выход из приложения private void Close(object sender, RoutedEventArgs e) { Application.Current.Shutdown(); } //Ограничение для ввода текста #region Ограничения //Для ввода только цифр private void numbertxt_PreviewTextInput(object sender, TextCompositionEventArgs e) { e.Handled = new Regex("[^0-9]+").IsMatch(e.Text); } //Для ввода только цифр private void telephonetxt_PreviewTextInput(object sender, TextCompositionEventArgs e) { e.Handled = new Regex("[^0-9]+").IsMatch(e.Text); } //Запрет пробела private void numbertxt_PreviewKeyDown(object sender, KeyEventArgs e) { if (e.Key == Key.Space) { e.Handled = true; } } //Запрет пробела private void telephonetxt_PreviewKeyDown(object sender, KeyEventArgs e) { if (e.Key == Key.Space) { e.Handled = true; } } #endregion //Добавление комнаты private void Add_Click(object sender, RoutedEventArgs e) { try { if (numbertxt.Text == "" || telephonetxt.Text == "") { MessageBox.Show("Заполните все поля!", "Предупреждение", MessageBoxButton.OK, MessageBoxImage.Information); } else if (numbertxt.Text.Length < 3 || telephonetxt.Text.Length < 9) { MessageBox.Show("Поля не полностью заполены!", "Предупреждение", MessageBoxButton.OK, MessageBoxImage.Information); } else { con.Open(); SqlCommand cmd = new SqlCommand("Select * from Room where Number_Room ='" + numbertxt.Text + "'", con); cmd.CommandType = CommandType.Text; SqlDataAdapter adapter = new SqlDataAdapter(); adapter.SelectCommand = cmd; DataSet dataSet = new DataSet(); adapter.Fill(dataSet); if (dataSet.Tables[0].Rows.Count > 0) { MessageBox.Show("Такая комната уже есть!", "Информация", MessageBoxButton.OK, MessageBoxImage.Information); con.Close(); } else { if (yescheck.IsChecked == true) status = "1"; else status = "2"; string sql = "INSERT INTO Room (Number_Room,Telephone_Room,Status_Room) VALUES('" + numbertxt.Text + "','" + telephonetxt.Text + "','" + status.ToString() + "')"; SqlDataAdapter dataAdapter = new SqlDataAdapter(sql, con); dataAdapter.SelectCommand.ExecuteNonQuery(); con.Close(); idroomtxt.Text = ""; numbertxt.Text = ""; telephonetxt.Text = ""; yescheck.IsChecked = true; showgrid(); MessageBox.Show("Комната добавлена!", "Предупреждение", MessageBoxButton.OK, MessageBoxImage.Information); } } } catch (Exception ex) { con.Close(); MessageBox.Show("Возникла ошибка! " + ex.ToString(), "Ошибка", MessageBoxButton.OK, MessageBoxImage.Error); } } //Обнавление комнаты private void Update_Click(object sender, RoutedEventArgs e) { try { if (idroomtxt.Text == "") { MessageBox.Show("Поле не выбрано! Выберите нужное поле!", "Предупреждение", MessageBoxButton.OK, MessageBoxImage.Information); } else if (numbertxt.Text == "" || telephonetxt.Text == "") { MessageBox.Show("Заполните все поля!", "Предупреждение", MessageBoxButton.OK, MessageBoxImage.Information); } else if (numbertxt.Text.Length < 3 || telephonetxt.Text.Length < 9) { MessageBox.Show("Поля не полностью заполены!", "Предупреждение", MessageBoxButton.OK, MessageBoxImage.Information); } else { try { if (yescheck.IsChecked == true) status = "1"; else status = "2"; con.Open(); string sql = "Update Room set Number_Room ='" + numbertxt.Text + "', Telephone_Room = '" + telephonetxt.Text + "', Status_Room = '" + status.ToString() + "' where ID_Room = '" + idroomtxt.Text + "'"; SqlDataAdapter dataAdapter = new SqlDataAdapter(sql, con); dataAdapter.SelectCommand.ExecuteNonQuery(); con.Close(); idroomtxt.Text = ""; numbertxt.Text = ""; telephonetxt.Text = ""; yescheck.IsChecked = true; showgrid(); MessageBox.Show("Комната изменена!", "Предупреждение", MessageBoxButton.OK, MessageBoxImage.Information); } catch (Exception ex) { con.Close(); MessageBox.Show("Возникла ошибка! " + ex.ToString(), "Ошибка", MessageBoxButton.OK, MessageBoxImage.Error); } } } catch (Exception ex) { MessageBox.Show("Возникла ошибка! " + ex.ToString(), "Ошибка", MessageBoxButton.OK, MessageBoxImage.Error); } } //Удаление комнаты private void Delete_Click(object sender, RoutedEventArgs e) { if (idroomtxt.Text == "") { MessageBox.Show("Поле не выбрано! Выберите нужное поле!", "Предупреждение", MessageBoxButton.OK, MessageBoxImage.Information); } else { try { con.Open(); string sql = "DELETE FROM Room WHERE ID_Room = '" + idroomtxt.Text + "'"; SqlDataAdapter dataAdapter = new SqlDataAdapter(sql, con); dataAdapter.SelectCommand.ExecuteNonQuery(); con.Close(); idroomtxt.Text = ""; numbertxt.Text = ""; telephonetxt.Text = ""; yescheck.IsChecked = true; showgrid(); MessageBox.Show("Комната удалена!", "Информация", MessageBoxButton.OK, MessageBoxImage.Information); } catch (Exception ex) { con.Close(); MessageBox.Show("Возникла ошибка! " + ex.ToString(), "Ошибка", MessageBoxButton.OK, MessageBoxImage.Error); } } } //Свернуть окно private void WindMin_Click(object sender, RoutedEventArgs e) { this.WindowState = WindowState.Minimized; } //Фомировка данных из БД void showgrid() { try { con.Open(); string sql = "SELECT ID_Room, Number_Room, Telephone_Room, RoomStatus.Status From Room inner join RoomStatus on RoomStatus.ID_Status = Room.Status_Room"; SqlDataAdapter dataAdapter = new SqlDataAdapter(sql, con); DataTable data = new DataTable("Room"); dataAdapter.Fill(data); dataroom.ItemsSource = data.DefaultView; dataAdapter.Update(data); con.Close(); dataroom.Columns[0].Header = "ID"; dataroom.Columns[1].Header = "Номер комнты"; dataroom.Columns[2].Header = "Телефон комнаты"; dataroom.Columns[3].Header = "Статус комнаты"; dataroom.Columns[0].Visibility = Visibility.Collapsed; } catch (Exception ex) { con.Close(); MessageBox.Show("Возникла ошибка! " + ex.ToString(), "Ошибка", MessageBoxButton.OK, MessageBoxImage.Error); } } //Выбор строки из БД private void dataroom_SelectionChanged(object sender, SelectionChangedEventArgs e) { try { DataGrid gd = (DataGrid)sender; DataRowView rowView = gd.SelectedItem as DataRowView; if (rowView != null) { idroomtxt.Text = rowView["ID_Room"].ToString(); numbertxt.Text = rowView["Number_Room"].ToString(); telephonetxt.Text = rowView["Telephone_Room"].ToString(); status = rowView["Status"].ToString(); if (status == "Свободна") yescheck.IsChecked = true; else nocheck.IsChecked = true; } } catch (Exception ex) { MessageBox.Show("Возникла ошибка! " + ex.ToString(), "Ошибка", MessageBoxButton.OK, MessageBoxImage.Error); } } //Обновление private void Refresh_Click(object sender, RoutedEventArgs e) { showgrid(); idroomtxt.Text = ""; numbertxt.Text = ""; telephonetxt.Text = ""; yescheck.IsChecked = true; } //Запуск в самом начале private void Window_Loaded(object sender, RoutedEventArgs e) { showgrid(); } } }