Hello! I created a registration and login form but I have a problem . When you created a user , you can create it again with different password .
Here is code of Registration form :
I want to do that when you create a new account first it check if username exists and then create or give an error . How can I make that?Code: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 MySql.Data.MySqlClient; namespace SyrX_Messenger { public partial class Reg : Form { private MySqlConnection conn; private string server; private string database; private string uid; private string password; public Reg() { server = "localhost"; database = "syrx"; uid = "root"; password = ""; string connString; connString = $"SERVER={server};DATABASE={database};UID={uid};PASSWORD={password}"; conn = new MySqlConnection(connString); InitializeComponent(); } private void Button2_Click(object sender, EventArgs e) { this.Hide(); var login = new Login(); login.Closed += (s, args) => this.Close(); login.Show(); } private void Button1_Click(object sender, EventArgs e) { if (TextBox3.Text == "") { MessageBox.Show("Please approve your password"); } else if (TextBox2.Text != TextBox3.Text) { MessageBox.Show("Passwords do not match"); } else { string user = TextBox1.Text; string pass = TextBox2.Text; if (Register(user, pass)) { MessageBox.Show($"User {user} successfully created"); } else { MessageBox.Show($"User {user} did not created!"); } } } public bool Register(string user, string pass) { string query = $"INSERT INTO users (id, username, password) VALUES ('', '{user}', '{pass}');"; try { if (OpenConnection()) { MySqlCommand cmd = new MySqlCommand(query, conn); try { cmd.ExecuteNonQuery(); return true; } catch (Exception ex) { return false; } } else { conn.Close(); return false; } } catch { conn.Close(); return false; } } private bool OpenConnection() { try { conn.Open(); return true; } catch (MySqlException ex) { switch (ex.Number) { case 0: MessageBox.Show("Can not connect to server"); break; case 1045: MessageBox.Show("Server error"); break; } return false; } } } }




Reply With Quote
