Click here to Skip to main content
15,887,472 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
When I want to click on back button private void Back_Click(object sender, EventArgs e) in Form2.cs, I want to create a code that will remember data in textboxes:
C#
 private void CompanyText_TextChanged(object sender, EventArgs e) , 
private void ServicesText_TextChanged(object sender, EventArgs e) , 
private void PortText_TextChanged(object sender, EventArgs e)

and
C#
private void ServerText_TextChanged(object sender, EventArgs e)
in Form1.cs.

What I have tried:

I've tried to create a code in Form1.cs Form1_Load and Form1_Activated but it does't work. My code in Form1.cs looks like this:

C#
 private void CompanyText_TextChanged(object sender, EventArgs e)
        {
            UpdateAllText();

            companyData = CompanyText.Text;
        }

        private void ServicesText_TextChanged(object sender, EventArgs e)
        {
            UpdateAllText();

            servicesData = ServicesText.Text;
        }

        private void PortText_TextChanged(object sender, EventArgs e)
        {
            UpdateAllText();

            portData = PortText.Text;
        }

        private void ServerText_TextChanged(object sender, EventArgs e)
        {
            UpdateAllText();

            serverName = ServerText.Text;

            serverData = ServerText.Text;
        }

private void PortText_Enter(object sender, EventArgs e)
        {
            if (PortText.Text == "")
            {
                PortText.Text = "4747";
            }
        }

        private void PortText_Leave(object sender, EventArgs e)
        {
            
        }

        private void ServicesText_Enter(object sender, EventArgs e)
        {
            if (ServicesText.Text == "")
            {
                ServicesText.Text = "";
            }
        }

        private void ServicesText_Leave(object sender, EventArgs e)
        {
            if (ServicesText.Text == "")
            {
                ServicesText.Text = "";
            }
        }

        private void UpdateAllText()
        {
            // Pobierz tekst z trzech TextBoxów i połącz je spacjami
            string companyText = CompanyText.Text;
            string servicesText = ServicesText.Text;
            string portText = PortText.Text;
            string serverText = ServerText.Text;

            // Uzyskaj nazwę komputera, na którym działa aplikacja
            string computerName = Dns.GetHostName();

            string serverName = ServerText.Text; // Przypisanie wartości do serverName

            // Połącz teksty spacjami
            string allText = $"Firma: {companyText} , Serwis: {servicesText} , Serwer: {serverText} , PortTCP: {portText}";

            // Ustaw połączony tekst w TextBoxie AllText
            AllText.Text = allText;
        }

        private void NextForm2_Click(object sender, EventArgs e)
        {
            AllForm1 = AllText.Text;
            Form2 form2 = new Form2();
            // Ustaw wartość SqlServerName w Form2 na ServerName z Form1
            form2.SqlServerName = ServerName;

            // Sprawdź, czy pole tekstowe CompanyText nie jest puste
            if (string.IsNullOrWhiteSpace(CompanyText.Text))
            {
                // Jeśli jest puste, wyświetl komunikat
                MessageBox.Show("Wpisz nazwę firmy", "Błąd", 
                MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            else if(string.IsNullOrWhiteSpace(ServicesText.Text))
            {
                // Jeśli jest puste, wyświetl komunikat
                MessageBox.Show("Wpisz nazwę serwisu", 
                 "Błąd", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

            using (SqlConnection connection = new SqlConnection($"Data Source={serverName};Integrated Security=True;"))
            {
                try
                {
                    // Serwer istnieje, możesz kontynuować do Form2.cs
                    connection.Open();

                    // Ustaw wartość SqlServerName w Form2 na serverName z Form1
                    form2.SqlServerName = serverName;

                    form2.Show();
                    this.Hide();
                }
                catch (SqlException)
                {
                    // Serwer nie istnieje, wyświetl MessageBox
                    MessageBox.Show("Nieznana nazwa serwera", "Błąd", 
                      MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            } 
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            CompanyText.Text = companyData;
            ServicesText.Text = servicesData;
            PortText.Text = portData;
            ServerText.Text = serverData;
        }

        private void Form1_Activated(object sender, EventArgs e)
        {
            CompanyText.Text = companyData;
            ServicesText.Text = servicesData;
            PortText.Text = portData;
            ServerText.Text = serverData;
        }


and my code in Form2.cs looks like this:
C#
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace WindowsFormsApp1
{
    public partial class Form2 : Form
    {
        public static string AllForm2 = "";
        private string sqlServerName;
        public string SqlServerName
        {
            get { return sqlServerName; }
            set { sqlServerName = value; }
        }

        public Form2()
        {
            InitializeComponent();
            CenterToScreen(); //wycentrowanie dialogu
        }
        public static string DataFromUsername { get; set; }
        private int failedAttempts=0; // Licznik nieudanych prób
        private bool buttonBlocked = false; // Flaga określająca, 
                      // czy przycisk jest zablokowany
        string connectionString = $"Server=localhost;Database=master;
        Integrated Security=True;"; // Zaktualizuj odpowiednio dane połączenia
        private string selectedUsername = "";
        private void Username_TextChanged(object sender, EventArgs e)
        {
            string[] allowedUsers = {
                "Test",
                "Gość",
                "Konto domyślne",
                "WDAGUtilityAccount",

                "Administrator"
            };
            string inputText = Username.Text.Trim();
            if (allowedUsers.Contains(inputText))
            {
                if (inputText == "Administrator")
                {
                    string allText = $"Domenowy i lokalny użytkownik: {inputText}";
                    // Ustaw połączony tekst w TextBoxie AllText
                    AllText2.Text = allText;
                }
                else
                {
                    string allText = $"Lokalny użytkownik: {inputText}";
                    AllText2.Text = allText;
                }
            }
            else
            {
                string allText = $"Nowy użytkownik: {inputText}";
                AllText2.Text = allText;
            }
            selectedUsername = Username.Text;
        }
        private void Back_Click(object sender, EventArgs e)
        {
            Form1 back1 = new Form1();
            back1.Show();
            this.Hide();
        }
        //-----------------------------------------------------------------
        private void UserExistRadioButton_CheckedChanged(object sender, EventArgs e)
        {
            if (UserExistRadioButton.Checked)
            {
                // Blokuj kontrolkę Username_TextChanged
                Username.Enabled = false;
                SecondPassword.Enabled = false;
                // Odblokuj kontrolkę ExistUserList_SelectedIndexChanged
                //ExistUserList.SelectedIndexChanged -= 
                           ExistUserList_SelectedIndexChanged;
                ExistUserList.Enabled = true;
                Username.Text = string.Empty;
                SecondPassword.Text = string.Empty;
            }
        }
        private void UserNotExistRadioButton_CheckedChanged(object sender, EventArgs e)
        {
            if (UserNotExistRadioButton.Checked)
            {
                // Odblokuj kontrolkę Username_TextChanged
                Username.Enabled = true;
                SecondPassword.Enabled = true;
                // Blokuj kontrolkę ExistUserList_SelectedIndexChanged
                //ExistUserList.SelectedIndexChanged += ExistUserList_SelectedIndexChanged;
                ExistUserList.Enabled = false;
            }
        }
        //-----------------------------------------------------------------
        private void ExistUserList_SelectedIndexChanged
                         (object sender, EventArgs e)
        {
            // Pobierz wybrany element z kontrolki ExistUserList
            string selectedText = ExistUserList.SelectedItem.ToString();
            // Ustaw wybrany tekst w kontrolce AllText2
            AllText2.Text = selectedText;
            if (ExistUserList.SelectedItem != null)
            {
                selectedUsername = ExistUserList.SelectedItem.ToString();
            }
            if (ExistUserList.SelectedItem != null 
            && ExistUserList.SelectedItem != "Administrator")
            {
                string selectedUser = ExistUserList.SelectedItem.ToString();
                AllText2.Text = "Lokalny użytkownik: " + selectedUser;
            }
            else if(ExistUserList.SelectedItem == "Administrator")
            {
                string selectedUser = ExistUserList.SelectedItem.ToString();
                AllText2.Text = "Domenowy i lokalny użytkownik: " + selectedUser;
            }
        }
        private void UpdateAllText2()
        {
            string username = Username.Text;
        }
        //-------------------------------------------------------------------------------------
        private void NextForm3_Click(object sender, EventArgs e)
        {
            string password = FirstPassword.Text;
            //string selectedUser = ExistUserList.SelectedItem.ToString();
            string[] dozwoloneNazwy = { "Test", "Gość", 
                      "Konto Domyślne", "WDAGUtilityAccount" };
            string wpisaneNazwa = Username.Text;
            string sqlServerName = SqlServerName;
            // Sprawdź, czy w haśle jest chociaż jedna liczba
            string password1 = FirstPassword.Text;
            bool containsDigit = false;
            foreach (char c in password1)
            {
                if (char.IsDigit(c))
                {
                    containsDigit = true;
                    break;
                }
            }
            // Sprawdź, czy w haśle jest chociaż jeden znak specjalny
            string password2 = FirstPassword.Text;
            bool containsSpecialCharacter = false;
            foreach (char c in password2)
            {
                if (!char.IsLetterOrDigit(c))
                {
                    containsSpecialCharacter = true;
                    break;
                }
            }
            // Sprawdź, czy hasło zawiera co najmniej jedną dużą literę
            string password3 = FirstPassword.Text;
            bool hasUpperCaseLetter = false;
            foreach (char character in password3)
            {
                if (char.IsUpper(character))
                {
                    hasUpperCaseLetter = true;
                    break;
                }
            }
            // Sprawdź, czy hasło zawiera co najmniej jedną dużą literę
            string password4 = FirstPassword.Text;
            bool hasLowerCaseLetter = false;
            foreach (char character in password4)
            {
                if (char.IsLower(character))
                {
                    hasUpperCaseLetter = true;
                    break;
                }
            }
            //.................................................................................
            if (Array.Exists(dozwoloneNazwy, nazwa => nazwa == wpisaneNazwa))
            {
                MessageBox.Show("Wybierz przycisk istniejący użytkownik i wybierz nazwę użytkownika z listy", "Błąd", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            else if (UserExistRadioButton.Checked==false && UserNotExistRadioButton.Checked == false)
            {
                MessageBox.Show("Wybierz przycisk nowy użytkownik lub istniejący użytkownik", "Błąd", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            else if (UserExistRadioButton.Checked)
            {
                if (buttonBlocked)
                {
                    MessageBox.Show("Przycisk jest zablokowany. Poczekaj 10 sekund.");
                    return;
                }
                if (ExistUserList.SelectedItem == null)
                {
                    // Wyświetl komunikat
                    MessageBox.Show("Wybierz istniejącą nazwę użytkownika",
                    "Błąd", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return; // Przerwij działanie metody, aby nie kontynuować
                }
                //..................................................................
                else if (ExistUserList.SelectedItem.ToString() == "Test")
                {
                    if (FirstPassword.Text != "zaq1@WSX")
                    {
                        failedAttempts++;
                        if (failedAttempts >= 3)
                        {
                            NextForm3.Enabled = false;
                            buttonBlocked = true;
                            FirstPassword.Enabled = false;
                            SecondPassword.Enabled = false;
                            FirstPassword.Text = string.Empty;
                            failedAttempts = 0; // Zerujemy liczbę nieudanych prób
                            MessageBox.Show("Podałeś złe hasło trzy razy. 
                            Przycisk zostanie zablokowany na 10 sekund.");
                            Timer timer = new Timer();
                            timer.Interval = 10000; // 10 sekund w milisekundach
                            timer.Tick += (s, ev) =>
                            {
                                NextForm3.Enabled = true;
                                buttonBlocked = false;
                                FirstPassword.Enabled = true;
                                SecondPassword.Enabled = false;
                                MessageBox.Show("Przycisk został odblokowany.");
                                timer.Stop();
                            };
                            timer.Start();
                        }
                        else
                        {
                            MessageBox.Show("Podałeś złe hasło. 
                            Pozostało prób: " + (3 - failedAttempts));
                        }
                    }
                    else
                    {
                        AllForm2 = AllText2.Text;
                        if (sender is Button NextForm3)
                        {
                            try
                            {
                                using (SqlConnection connection = 
                                  new SqlConnection(connectionString))
                                {
                                    connection.Open();
                                    string query = $"SELECT COUNT(*) FROM sys._principals WHERE name = @Username";
                                    using (SqlCommand command = 
                                     new SqlCommand(query, connection))
                                    {
                                        command.Parameters.AddWithValue("@Username", selectedUsername);
                                        int count = (int)command.ExecuteScalar();
                                        if (count > 0)
                                        {
                                            // Połączono użytkownika z bazą danych
                                            MessageBox.Show("Połączono użytkownika: " + selectedUsername + " z bazą danych");
                                            // Teraz sprawdź, czy użytkownik jest super adminem
                                            string isAdminQuery = "SELECT IsSuperAdmin FROM TabelaUzytkownikow WHERE NazwaUzytkownika = @NazwaUzytkownika";
                                            using (SqlCommand adminCommand = new SqlCommand(isAdminQuery, connection))
                                            {
                                                adminCommand.Parameters.AddWithValue("@NazwaUzytkownika", selectedUsername);
                                                bool isSuperAdmin = (bool)adminCommand.ExecuteScalar();
                                                // Wyświetl odpowiedni komunikat MessageBox
                                                if (isSuperAdmin)
                                                {
                                                    MessageBox.Show("Użytkownik: " + selectedUsername + " jest super adminem");
                                                }
                                                else
                                                {
                                                    MessageBox.Show("Użytkownik: " + selectedUsername + " nie jest super adminem");
                                                }
                                            }
                                        }
                                        else
                                        {
                                            MessageBox.Show("Użytkownik o nazwie: " + selectedUsername + " nie istnieje w bazie danych");
                                        }
                                    }
                                }
                            }
                            catch (Exception ex)
                            {
                                MessageBox.Show("Błąd połączenia z bazą danych: " + ex.Message, "Błąd", 
                          MessageBoxButtons.OK, MessageBoxIcon.Error);
                            }
                            Form3 next3 = new Form3();
                            next3.Show();
                            this.Close();
                        }
                    }
                }
                else if(ExistUserList.SelectedItem.ToString() == "Administrator")
                {
                    if (FirstPassword.Text != "ZAQ!2wsx")
                    {
                        failedAttempts++;
                        if (failedAttempts >= 3)
                        {
                            NextForm3.Enabled = false;
                            buttonBlocked = true;
                            FirstPassword.Enabled = false;
                            SecondPassword.Enabled = false;
                            FirstPassword.Text = string.Empty;
                            failedAttempts = 0; // Zerujemy liczbę nieudanych prób
                            MessageBox.Show("Podałeś złe hasło trzy razy. Przycisk zostanie zablokowany na 10 sekund.");
                            Timer timer = new Timer();
                            timer.Interval = 10000; // 10 sekund w milisekundach
                            timer.Tick += (s, ev) =>
                            {
                                NextForm3.Enabled = true;
                                buttonBlocked = false;
                                FirstPassword.Enabled = true;
                                SecondPassword.Enabled = false;
                                MessageBox.Show("Przycisk został odblokowany.");
                                timer.Stop();
                            };
                            timer.Start();
                        }
                        else
                        {
                            MessageBox.Show("Podałeś złe hasło. Pozostało prób: " + (3 - failedAttempts));
                        }
                    }
                    else
                    {
                        string inputText = Username.Text.Trim();
                        string allText = $"Domenowy i lokalny użytkownik: {inputText}";
                        AllForm2 = AllText2.Text;
                        if (sender is Button NextForm3)
                        {
                            try
                            {
                                using (SqlConnection connection = new SqlConnection(connectionString))
                                {
                                    connection.Open();
                                    string query = $"SELECT COUNT(*) FROM sys.server_principals WHERE name = @Username";
                                    using (SqlCommand command = new SqlCommand(query, connection))
                                    {
                                        command.Parameters.AddWithValue("@Username", selectedUsername);
                                        int count = (int)command.ExecuteScalar();
                                        MessageBox.Show("Połączono użytkownika: " + selectedUsername + " z bazą danych");
                                    }
                                }
                            }
                            catch (Exception ex)
                            {
                                MessageBox.Show("Błąd połączenia z bazą danych: " + ex.Message, "Błąd", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            }
                            Form3 next3 = new Form3();
                            next3.Show();
                            this.Close();
                        }
                    }
                }
                else if(ExistUserList.SelectedItem.ToString() == "Konto domyślne")
                {
                    if (FirstPassword.Text != "xsw2!QAZ")
                    {
                        failedAttempts++;

                        if (failedAttempts >= 3)
                        {
                            NextForm3.Enabled = false;
                            buttonBlocked = true;
                            FirstPassword.Enabled = false;
                            SecondPassword.Enabled = false;
                            FirstPassword.Text = string.Empty;
                            failedAttempts = 0; // Zerujemy liczbę nieudanych prób
                            MessageBox.Show("Podałeś złe hasło trzy razy. Przycisk zostanie zablokowany na 10 sekund.");
                            Timer timer = new Timer();
                            timer.Interval = 10000; // 10 sekund w milisekundach
                            timer.Tick += (s, ev) =>
                            {
                                NextForm3.Enabled = true;
                                buttonBlocked = false;
                                FirstPassword.Enabled = true;
                                SecondPassword.Enabled = false;
                                MessageBox.Show("Przycisk został odblokowany.");
                                timer.Stop();
                            };
                            timer.Start();
                        }
                        else
                        {
                            MessageBox.Show("Podałeś złe hasło. Pozostało prób: " + (3 - failedAttempts));
                        }
                    }
                    else
                    {
                        AllForm2 = AllText2.Text;
                        if (sender is Button NextForm3)
                        {
                            try
                            {
                                using (SqlConnection connection = new SqlConnection(connectionString))
                                {
                                    connection.Open();
                                    string query = $"SELECT COUNT(*) FROM sys.server_principals WHERE name = @Username";
                                    using (SqlCommand command = new SqlCommand(query, connection))
                                    {
                                        command.Parameters.AddWithValue("@Username", selectedUsername);
                                        int count = (int)command.ExecuteScalar();
                                        MessageBox.Show("Połączono użytkownika: " + selectedUsername + " z bazą danych");
                                    }
                                }
                            }
                            catch (Exception ex)
                            {
                                MessageBox.Show("Błąd połączenia z bazą danych: " + ex.Message, "Błąd", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            }
                            Form3 next3 = new Form3();
                            next3.Show();
                            this.Close();
                        }
                    }
                }
                else if(ExistUserList.SelectedItem.ToString() == "Gość")
                {
                    if (FirstPassword.Text != "XSW@1qaz")
                    {
                        failedAttempts++;

                        if (failedAttempts >= 3)
                        {
                            NextForm3.Enabled = false;
                            buttonBlocked = true;
                            FirstPassword.Enabled = false;
                            SecondPassword.Enabled = false;
                            FirstPassword.Text = string.Empty;
                            failedAttempts = 0; // Zerujemy liczbę nieudanych prób
                            MessageBox.Show("Podałeś złe hasło trzy razy. Przycisk zostanie zablokowany na 10 sekund.");
                            Timer timer = new Timer();
                            timer.Interval = 10000; // 10 sekund w milisekundach
                            timer.Tick += (s, ev) =>
                            {
                                NextForm3.Enabled = true;
                                buttonBlocked = false;
                                FirstPassword.Enabled = true;
                                SecondPassword.Enabled = false;
                                MessageBox.Show("Przycisk został odblokowany.");
                                timer.Stop();
                            };
                            timer.Start();
                        }
                        else
                        {
                            MessageBox.Show("Podałeś złe hasło. Pozostało prób: " + (3 - failedAttempts));
                        }
                    }
                    else
                    {
                        AllForm2 = AllText2.Text;
                        if (sender is Button NextForm3)
                        {
                            try
                            {
                                using (SqlConnection connection = new SqlConnection(connectionString))
                                {
                                    connection.Open();

                                    string query = $"SELECT COUNT(*) FROM sys.server_principals WHERE name = @Username";
                                    using (SqlCommand command = new SqlCommand(query, connection))
                                    {
                                        command.Parameters.AddWithValue("@Username", selectedUsername);
                                        int count = (int)command.ExecuteScalar();
                                        MessageBox.Show("Połączono użytkownika: " + selectedUsername + " z bazą danych");
                                    }
                                }
                            }
                            catch (Exception ex)
                            {
                                MessageBox.Show("Błąd połączenia z bazą danych: " + ex.Message, "Błąd", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            }
                            Form3 next3 = new Form3();
                            next3.Show();
                            this.Close();
                        }
                    }
                }
                else if(ExistUserList.SelectedItem.ToString() == "WDAGUtilityAccount")
                {
                    if (FirstPassword.Text != "Inczrob53!")
                    {
                        failedAttempts++;
                        if (failedAttempts >= 3)
                        {
                            NextForm3.Enabled = false;
                            buttonBlocked = true;
                            FirstPassword.Enabled = false;
                            SecondPassword.Enabled = false;
                            FirstPassword.Text = string.Empty;
                            failedAttempts = 0; // Zerujemy liczbę nieudanych prób
                            MessageBox.Show("Podałeś złe hasło trzy razy. Przycisk zostanie zablokowany na 10 sekund.");
                            Timer timer = new Timer();
                            timer.Interval = 10000; // 10 sekund w milisekundach
                            timer.Tick += (s, ev) =>
                            {
                                NextForm3.Enabled = true;
                                buttonBlocked = false;
                                FirstPassword.Enabled = true;
                                SecondPassword.Enabled = false;
                                MessageBox.Show("Przycisk został odblokowany.");
                                timer.Stop();
                            };
                            timer.Start();
                        }
                        else
                        {
                            MessageBox.Show("Podałeś złe hasło. Pozostało prób: " + (3 - failedAttempts));
                        }
                    }
                    else
                    {
                        AllForm2 = AllText2.Text;
                        if (sender is Button NextForm3)
                        {
                            try
                            {
                                using (SqlConnection connection = new SqlConnection(connectionString))
                                {
                                    connection.Open();
                                    string query = $"SELECT COUNT(*) FROM sys.server_principals WHERE name = @Username";
                                    using (SqlCommand command = new SqlCommand(query, connection))
                                    {
                                        command.Parameters.AddWithValue("@Username", selectedUsername);
                                        int count = (int)command.ExecuteScalar();
                                        MessageBox.Show("Połączono użytkownika: " + selectedUsername + " z bazą danych");
                                    }
                                }
                            }
                            catch (Exception ex)
                            {
                                MessageBox.Show("Błąd połączenia z bazą danych: " + ex.Message, "Błąd", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            }
                            Form3 next3 = new Form3();
                            next3.Show();
                            this.Close();
                        }
                    }
                }
                //.................................................................
                // Sprawdź, czy został wybrany element z listy
                if (ExistUserList.SelectedItem != null)
                {
                    string selectedUsername = ExistUserList.SelectedItem.ToString();
                    string connectionString = $"Server={sqlServerName};Database=master;Integrated Security=True;";
                    using (SqlConnection connection = new SqlConnection(connectionString))
                    {
                        try
                        {
                            connection.Open();
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show("Wystąpił błąd: " + ex.Message);
                        }
                        finally
                        {
                            connection.Close();
                        }
                    }
                }
                else
                {
                    MessageBox.Show("Proszę wybrać użytkownika z listy.");
                }
            }
            // Sprawdzamy, czy przycisk radio UserNotExistRadioButton jest zaznaczony
            else if (UserNotExistRadioButton.Checked)
            {
                // Sprawdzamy, czy pole Username nie jest puste
                if (string.IsNullOrEmpty(Username.Text))
                {
                    MessageBox.Show("Musisz wpisać nazwę użytkownika", "Błąd", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                else if (Username.Text.Length < 3)
                {
                    MessageBox.Show("Musisz wpisać 3 lub więcej liter w nazwie użytkownika", "Błąd", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                else if (FirstPassword.Text != SecondPassword.Text)
                {
                    failedAttempts++;

                    if (failedAttempts >= 3)
                    {
                        NextForm3.Enabled = false;
                        buttonBlocked = true;
                        FirstPassword.Enabled = false;
                        SecondPassword.Enabled = false;
                        FirstPassword.Text = string.Empty;
                        SecondPassword.Text = string.Empty;
                        failedAttempts = 0; // Zerujemy liczbę nieudanych prób
                        MessageBox.Show("Podałeś złe hasło trzy razy. Przycisk zostanie zablokowany na 10 sekund.");
                        Timer timer = new Timer();
                        timer.Interval = 10000; // 10 sekund w milisekundach
                        timer.Tick += (s, ev) =>
                        {
                            NextForm3.Enabled = true;
                            buttonBlocked = false;
                            FirstPassword.Enabled = true;
                            SecondPassword.Enabled = true;

                            MessageBox.Show("Przycisk został odblokowany.");
                            timer.Stop();
                        };
                        timer.Start();
                    }
                    else
                    {
                        MessageBox.Show("Hasła muszą być takie same. Pozostało prób: " + (3 - failedAttempts));
                    }
                }
                else if (string.IsNullOrEmpty(FirstPassword.Text) && string.IsNullOrEmpty(SecondPassword.Text) && password.Length < 8)
                {
                    MessageBox.Show("Musisz wpisać hasło, powtórzyć hasło, musisz wpisać 8 znaków w haśle", "Błąd", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                else if (!containsDigit && !containsSpecialCharacter && !hasUpperCaseLetter && !hasLowerCaseLetter)
                {
                    MessageBox.Show("Musisz wpisać chociażby jedną liczbę w haśle." +
                                    "Musisz wpisać chociażby jeden znak specjalny w haśle" +
                                    "Musisz wpisać chociażby jedną dużą literę w haśle" +
                                    "Musisz wpisać chociażby jedną mniejszą literę w haśle", "Błąd", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                else
                {
                    AllForm2 = AllText2.Text;
                    try
                    {
                        using (SqlConnection connection = new SqlConnection(connectionString))
                        {
                            connection.Open();
                            string query = $"SELECT COUNT(*) FROM sys.server_principals WHERE name = @Username";
                            using (SqlCommand command = new SqlCommand(query, connection))
                            {
                                command.Parameters.AddWithValue("@Username", selectedUsername);
                                int count = (int)command.ExecuteScalar();
                                MessageBox.Show("Połączono użytkownika: " + selectedUsername + " z bazą danych");
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("Błąd połączenia z bazą danych: " + ex.Message, "Błąd", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    Form3 next3 = new Form3();
                    next3.Show();
                    this.Close();
                }
            }
        }
        private void AllText2_TextChanged(object sender, EventArgs e)
        {

        }
    }
}
Posted
Updated 19-Oct-23 5:17am
v2

C#
private void Back_Click(object sender, EventArgs e)
{
    Form1 back1 = new Form1();
    back1.Show();
    this.Hide();
}

Assuming this is the code that's called when you click the back button in your app, your code is creating a new instance of Form1 and showing it. It will not remember anything about the last instance of Form1 that you supposedly came from. Before destroying the old instance of Form1, your code has to save all the data it wants to appear on Form1 again when you click back and create a new instance of Form1. It has to repopulate all the controls from the data you saved.
 
Share this answer
 
Take a look at the three tips starting with Transferring information between two forms, Part 1: Parent to Child[^], by the esteemed OriginalGriff.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900