I want to enter details of a client into a database.If the details already exists the application must inform the user and they don't then save the details

here is my code

private void btnCreate_Click(object sender, EventArgs e)
        {
            SqlConnection conn = new SqlConnection();
            conn.ConnectionString="Data Source=MyComputer\\SQLEXPRESS;Initial Catalog=TIP;Integrated Security=True;Pooling=False";
            conn.Open();
            string check = "SELECT COUNT(UserID)FROM Login WHERE UserID='"+txtID.Text+"'";
            string input="INSERT INTO Login(UserID,UserName,Password,Station)VALUES('"+txtClientID.Text+"','"+txtClientName.Text+"','"+txtPass.Text+"','"+ClientRank.Text+"')";
            SqlCommand cd = new SqlCommand(check, conn);
            SqlCommand com = new SqlCommand(input, conn);
            cd.CommandText = check;
            SqlDataReader dr;
            dr = cd.ExecuteReader();
            if (dr.HasRows==false)
            {
                MessageBox.Show("UserID Already Assigned");
                dr.Close();
                Chidzima();
            }
            else if (dr.HasRows==true)
            {
                com.CommandText = input;
                com.ExecuteNonQuery();
                MessageBox.Show("Details Saved", "Valid Data", MessageBoxButtons.OK, MessageBoxIcon.Information);
                Chidzima();
            }
            else
            {
            }
            
            
            
            conn.Close();
        }
        public void Chidzima()
        {
            txtID.Clear();
            txtPass.Clear();
            txtUser.Clear();
            cmbSta.Text = "";
        }
    }

I am new to c# help me please!!

Dani AI

Generated

Quick diagnosis and practical fixes.

The main problem is a mismatch between the SQL used and the way the result is checked. A SELECT COUNT(...) always returns one row (the numeric count), so an ExecuteReader/HasRows check will be misleading — the reader has a row even when the count is 0. That explains the strange behavior. Also the logic is inverted in the posted code (insert should happen when no user is found), and there are inconsistent textbox names (txtID vs txtClientID, txtUser vs txtClientName) that commonly cause the check to run against the wrong value. 's suggestion to call Read() and 's note about the inverted check are both useful; a cleaner approach is to use a parameterized, atomic check+insert or a simple scalar existence check.

A robust pattern (atomic, parameterized, avoids SQL injection and race conditions) is shown here:

using (var conn = new SqlConnection(connString))
{
    conn.Open();
    var sql = @"
IF NOT EXISTS (SELECT 1 FROM Login WHERE UserID = @id)
BEGIN
  INSERT INTO Login (UserID, UserName, PasswordHash, Station) 
  VALUES (@id, @name, @pass, @station);
  SELECT 1;
END
ELSE
  SELECT 0;";
    using (var cmd = new SqlCommand(sql, conn))
    {
        cmd.Parameters.AddWithValue("@id", txtClientID.Text.Trim());
        cmd.Parameters.AddWithValue("@name", txtClientName.Text.Trim());
        cmd.Parameters.AddWithValue("@pass", HashPassword(txtPass.Text));
        cmd.Parameters.AddWithValue("@station", cmbSta.Text.Trim());
        var inserted = Convert.ToInt32(cmd.ExecuteScalar());
        if (inserted == 1) MessageBox.Show("Details saved");
        else MessageBox.Show("UserID already assigned");
    }
}

Additional notes: enforce uniqueness at the database level (unique index/constraint) and handle SqlException numbers 2627/2601 if relying on constraint violations; never concatenate user input into SQL; store password hashes, not plain text; use using to auto-close connections. Quick troubleshooting checklist: confirm the exact textbox names and values used in the check, run the check-query directly in SQL Server Management Studio with that value, and verify the connection string and table schema.

Recommended Answers

All 6 Replies

Call the Read() method.

...
   if (dr.Read())
            {
                MessageBox.Show("UserID Already Assigned");
                dr.Close();
                Chidzima();
            }
 ....

Firstly, Please use [code]

[/code] blocks when posting code. This ensures teh correct formatting to make ti more readable.

Secondly, you are inserting the values if dr.HasRows == true. This should be the other way around. If dr.HasRows is true then it means the user was found in the database and returned by your check query.
If HasRows is false, then no user was found and you should insert it.

Thanx but its executing only the if statement which outputs "USERID ALREADY ASSIGNED" Message. Is there anything wrong with my sql statements??

Change sql text,

string check = "SELECT  UserID FROM Login WHERE UserID='"+txtID.Text+"'";

Thanx

my bad, overlooked that the check returned count, not rows the actual rows found : /

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.