Exemple #1
0
        private void ListViewRabbits_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (ListViewRabbits.SelectedItem != null)
            {
                // select rabbit by casting to Rabbit type the object select in ListView
                rabbit = (Rabbit)ListViewRabbits.SelectedItem;
                TextBoxRabbitId.Text   = rabbit.RabbitId.ToString();
                TextBoxRabbitName.Text = rabbit.RabbitName;
                TextBoxRabbitAge.Text  = rabbit.Age.ToString();
            }

            // show data as read only
            TextBoxRabbitId.IsReadOnly   = true;
            TextBoxRabbitName.IsReadOnly = true;
            TextBoxRabbitAge.IsReadOnly  = true;
            // set edit button to active
            ButtonEdit.IsEnabled = true;
        }
Exemple #2
0
        private void ButtonAddRabbit_Click(object sender, RoutedEventArgs e)
        {
            if (ButtonAddRabbit.Content.ToString() == "Add Rabbit")
            {
                // text boxes now become editable
                TextBoxRabbitName.IsReadOnly = false;
                TextBoxRabbitAge.IsReadOnly  = false;
                // clear all text boxes
                TextBoxRabbitId.Text   = "";
                TextBoxRabbitName.Text = "";
                TextBoxRabbitAge.Text  = "";

                ButtonAddRabbit.Content = "Save";
            }
            else
            {
                // save new rabbit to database
                if (TextBoxRabbitName.Text.Length > 0)
                {
                    Int32.TryParse(TextBoxRabbitAge.Text, out int rabbitage);

                    var rabbitToAdd = new Rabbit()
                    {
                        RabbitName = TextBoxRabbitName.Text,
                        Age        = rabbitage
                    };
                    // get database into memory (db = local computer copy of database)
                    using (var db = new RabbitDatabaseEntities()) {
                        db.Rabbits.Add(rabbitToAdd);
                        db.SaveChanges();

                        // update list
                        // firstly set to null
                        ListViewRabbits.ItemsSource = null;
                        // secondsly re-read rabbits afresh from database
                        rabbits = db.Rabbits.ToList();
                        ListViewRabbits.ItemsSource = rabbits;
                    }
                }
                ButtonAddRabbit.Content = "Add Rabbit";
            }
        }