Click here to Skip to main content
15,886,963 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I want to create a code in VS2017 Windows Forms that will add users to SQL Server automatically: id, username, first password, second password (repeated password) in database SQL Server Management Studio. That's my code in Form1:
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;

namespace WindowsFormsApp1
{
    public partial class Form1 : Form
    {
        public static string AllForm1 = "";

        public Form1()
        {
            InitializeComponent();
        }

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

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

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

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

        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;

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

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

        private void NextForm2_Click(object sender, EventArgs e)
        {
            AllForm1 = AllText.Text;

            // 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);
            }
            else
            {
                Form2 next2 = new Form2();
                next2.Show();
                this.Close();
            }
        }

        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 AllText_TextChanged(object sender, EventArgs e)
        {

        }
    }
}


That's my Form2 code:

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 = "";
        public Form2()
        {
            InitializeComponent();
        }

        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

        private void Username_TextChanged(object sender, EventArgs e)
        {
            string[] allowedUsers = {
                /*
                "Dorota Gruzdas",
                "Edyta Wandzlewicz",
                "Karolina Domżał",
                "Łukasz Kiczko",
                "Maciej Rzeszutek",
                "Magdalena Skrzypińska",
                "Marek Cybowski",
                "Marek Skrzypiński",
                "Mariusz Golubiński",
                "Marta Wojtkiewicz",
                "Mateusz Miękicki",
                "Michał Piotrowski",
                "Paulina Bułygo",
                "Paweł Winckiewicz",
                "Robert Inczewski",
                "Sławomir Rusajczyk",

                "dhcp",
                "Guest",
                "Skaner",
                "Szarak Pospolity",
                "Użytkownik Projektu",
                */

                "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;
            }
        }

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

        //-----------------------------------------------------------------

        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 && 
                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 SecondPassword_TextChanged(object sender, EventArgs e)
        {
            
        }

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

        //-----------------------------------------------------------------

        private void UpdateAllText2()
        {
            string username = Username.Text;

            // Połącz teksty spacjami            
        }

        //-------------------------------------------------------------------

        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;

            // 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)
                        {
                            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)
                        {
                            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)
                        {
                            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)
                        {
                            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)
                        {
                            Form3 next3 = new Form3();
                            next3.Show();
                            this.Close();
                        }
                    }
                }
            }

            // 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;

                    Form3 next3 = new Form3();
                    next3.Show();
                    this.Close();
                }
            }
            //.....................................................................

            // Pobierz dane z TextBox'ów
            string serverName = "localhost";
            string username = Username.Text;
            string fstpassword = FirstPassword.Text;

            // Tworzenie łańcucha połączenia
            string connectionString = $"Data Source={serverName};
            Initial Catalog=TwojaBazaDanych;User ID={username};
            Password={fstpassword};";

            // Tworzenie obiektu SqlConnection
            SqlConnection connection = new SqlConnection(connectionString);

            try
            {
                // Otwarcie połączenia
                connection.Open();
                MessageBox.Show("Połączono z bazą danych!");

                // Tutaj możesz dodać kod obsługujący połączenie z bazą danych

                // Np. możesz wykonać zapytanie SQL lub otworzyć 
                // nowe okno z danymi z bazy danych
            }
            catch (Exception ex)
            {
                MessageBox.Show($"Błąd połączenia: {ex.Message}");
            }
            finally
            {
                // Zawsze zamykaj połączenie, gdy nie jest już potrzebne
                if (connection.State == System.Data.ConnectionState.Open)
                {
                    connection.Close();
                }
            }
        }

        //------------------------------------------------------------------

        private void AllText2_TextChanged(object sender, EventArgs e)
        {

        }        
    }
}

That's my Form3 code:
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;

namespace WindowsFormsApp1
{
    public partial class Form3 : Form
    {
        public Form3()
        {
            InitializeComponent();
            AllText3.Text = Form1.AllForm1 + "\r\n" + Form2.AllForm2;
        }

        private void Back_Click(object sender, EventArgs e)
        {
            Form2 back2 = new Form2();
            back2.Show();
            this.Close();
        }

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


What I have tried:

I have added in Windows Forms texboxes: username, first_password, second_password and I've connected database from SQL Server to VS2017 Windows Forms.
Posted
Updated 3-Oct-23 5:17am
v2
Comments
Richard Deeming 3-Oct-23 10:06am    
You seem to have forgotten to ask a question. Dumping hundreds of lines of unexplained code without any description of what the problem is, what you have tried, and where you are stuck, is not going to get you any help.

1 solution

First off, you don't need to store the same password twice, if that's what you are planning: compare them when he registers to make sure they are the same, but if they are you don't need both ever again - just the one copy.
Second, it is your legal duty to keep passwords safe, and that means not storing them in plain text. See here: Password Storage: How to do it.[^]

Thirdly, if you don't know how to insert and retrieve data to / from a database, see here: Basic Database Operations Using C# - GeeksforGeeks[^]
 
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