Exemple #1
0
 public MainWindow()
 {
     InitializeComponent();
     try
     {
         ctx = new FlightsDBContext();
         var v = (from p in ctx.Flight select p).ToList();
         flightList            = new ObservableCollection <Flight>(v);
         lvFlights.DataContext = flightList;
     }
     catch (System.IO.InvalidDataException ex)
     {
         MessageBox.Show("Error opening database connection: " + ex.Message);
         Environment.Exit(1);
     }
 }
        private void btSave_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                Flight   flight   = (currentItem == null ? new Flight() : currentItem);
                string   onDayStr = tbDate.Text;
                DateTime newDate;
                if (!DateTime.TryParse(onDayStr, out newDate))
                {
                    throw new System.IO.InvalidDataException("Can't make OnDay!");
                }
                flight.OnDay    = newDate;
                flight.FromCode = tbFromCode.Text;
                flight.ToCode   = tbToCode.Text;

                var value = infoFlights.SelectedItem ?? throw new System.IO.InvalidDataException("The info was not selected!");
                // Try to convert the string to an enum:
                TypeFlights typeFlight = (TypeFlights)Enum.Parse(typeof(TypeFlights), value.ToString());
                flight.TypeFlight = typeFlight;


                string passengerStr = tbPassenger.Text;
                int    passengerInt = 0;
                if (!Int32.TryParse(passengerStr, out passengerInt))
                {
                    throw new System.IO.InvalidDataException("Can't convert string to int with passenger!");
                }
                flight.Passenger = passengerInt;
                // add and edit - insert
                FlightsDBContext ctx = MainWindow.ctx;
                if (currentItem == null)
                {
                    ctx.Flight.Add(flight);
                }
                ctx.SaveChanges();
                DialogResult = true;
            }
            catch (SqlException ex)
            {
                MessageBox.Show("Error: Database add/update error!" + ex.Message, "Error Message");
            }
            catch (System.IO.InvalidDataException ex)
            {
                MessageBox.Show("Error:" + ex.Message, "Error Message");
            }
        }