Beispiel #1
0
        private void Add_Click(object sender, RoutedEventArgs e)
        {
            mConnection = DatabaseManager.CreateConnectionToDatabase();

            if (FirstName.Text != string.Empty && LastName.Text != string.Empty && Email.Text != string.Empty && Supervisor.Text != string.Empty)
            {
                int newId = 0;
                mConnection.Open();
                using (mConnection)
                {//SELECT TOP 1 * FROM Table ORDER BY ID DESC
                    string queryMax = "SELECT TOP 1 User_Id FROM Users_ ORDER BY User_Id DESC";
                    using (SqlCommand command1 = new SqlCommand(queryMax, mConnection))
                    {
                        SqlDataReader reader = command1.ExecuteReader();
                        reader.Read();
                        newId = int.Parse(reader[0].ToString());
                        newId++;
                        mConnection.Close();
                    }
                }

                mConnection = DatabaseManager.CreateConnectionToDatabase();
                using (mConnection)
                {
                    string query = "INSERT INTO Users_ (User_Id, FirstName, LastName, email,password, Supervisor, Classification) VALUES (@User_Id, @FirstName, @LastName, @email, 'Team1',@Supervisor, @Classification)";
                    mConnection.Open();
                    using (SqlCommand command = new SqlCommand(query, mConnection))
                    {
                        command.Parameters.AddWithValue("@User_Id", newId);
                        command.Parameters.AddWithValue("@FirstName", FirstName.Text);
                        command.Parameters.AddWithValue("@LastName", LastName.Text);
                        command.Parameters.AddWithValue("@email", Email.Text);
                        command.Parameters.AddWithValue("@Supervisor", Supervisor.Text);
                        command.Parameters.AddWithValue("@Classification", Classification.Text);

                        int result = command.ExecuteNonQuery();

                        if (result < 0)
                        {
                            Console.WriteLine("Error inserting data into Database!");
                        }
                        else
                        {
                            MessageBox.Show("User successfully saved! Id number: " + newId);

                            FirstName.Clear();
                            LastName.Clear();
                            Email.Clear();
                            Supervisor.Clear();
                        }
                    }
                }
            }
            else
            {
                MessageBox.Show("Empty field detected, please fill in everything");
            }

            mConnection.Close();
        }