Try this, but you need to change your connection string to your own. I have made many comments inline so I will keep this post to a minimum. If it helps, mark it as your answer. Any questions let me know. I've fixed a number of mistakes and commented some of them.
I've changed a lot of your code, and although I didn't write you a properly structured reusable robust class, as I didn't have time, but you should learn to utilise class development to your advantage, as you can make a lot of reusable code by doing so. Your problem is fixed for the most part.
Screenshot:
https://prnt.sc/kv84hb[
^]
using MySql.Data.MySqlClient;
using System;
using System.Data;
using System.Windows.Forms;
namespace TestCSharpApp
{
public partial class Form1 : System.Windows.Forms.Form
{
private static string cString = "server=localhost;user id=root;password=root;persistsecurityinfo=True;database=visuals_db;port=3306";
private static MySqlConnection Con = new MySqlConnection(cString);
public Form1()
{
InitializeComponent();
}
private void btnRegister_Click(object sender, EventArgs e)
{
string Fname = "John doe";
string Uname = "JohnDoe1";
string Email = "me@myemail.com";
string Pass = "mypass123";
if (Register(Fname, Uname, Email, Pass))
{
MessageBox.Show("User has been Created");
}
else
{
MessageBox.Show("User has not been Created");
}
}
public bool Register(String Fname, String Uname, String Email, String Pass)
{
string execQuery = "INSERT INTO users (name,username,email,password) VALUES (@Fname,@Uname,@Email,@Pass)";
try
{
if (Con != null && Con.State == ConnectionState.Closed)
{
Con.Open();
using (MySqlCommand cmd = new MySqlCommand(execQuery, Con))
{
cmd.Parameters.AddWithValue("@Fname", Fname);
cmd.Parameters.AddWithValue("@Uname", Uname);
cmd.Parameters.AddWithValue("@Email", Email);
cmd.Parameters.AddWithValue("@Pass", Pass);
cmd.ExecuteNonQuery();
}
Con.Close();
return true;
}
return true;
}
catch (NullReferenceException nullRefEx)
{
MessageBox.Show(nullRefEx.Message);
Con.Close();
return false;
}
catch (MySqlException sqlErr)
{
return false;
}
catch (Exception ex)
{
return false;
}
finally
{
}
}
}
}