Máté Antal Máté Antal - 1 year ago 208
SQL Question

C# Check if the username is not null or empty nor already taken

As i said, I want to check in the Register that the username isn't null, or empty

nor already taken.

static SqlConnection Con = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=heres_the_path;Integrated Security=True");
static string name,pass,email;
static DataTable dt = new DataTable();

Please help me fix the code, the problem is somewhere here:

static bool IsUsernameAlreadyTaken(string name)//Username Checker
SqlDataAdapter sda = new SqlDataAdapter("SELECT count(*) FROM Login WHERE Nev='" + name + "'", Con);
if (dt.Rows[0][0].ToString() == "1") return true;
else return false;

Or in this while loop:

static void Register() {
Console.WriteLine("What will be your username?");
while (string.IsNullOrEmpty(name) && IsUsernameAlreadyTaken(name)==false)
name = Console.ReadLine();
if (IsUsernameAlreadyTaken(name))
Console.WriteLine("That's already taken");
if (string.IsNullOrEmpty(name))

Now if I give the program a name which already exist in the database it doesn't tell me that it's already taken, just continuous.

Answer Source

The problem is here:

while (string.IsNullOrEmpty(name) && IsUsernameAlreadyTaken(name)==false)

What you're asking the code to do is this:

  1. Check to ensure that name is null or empty
  2. If it is null or empty, check to see if it is already taken.

Obviously this logic is seriously flawed.

Did you mean this?

while (string.IsNullOrEmpty(name) || IsUsernameAlreadyTaken(name)==false)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download