i made login and registration page .the code for the registration page is working fine but not login.

_ ati 111 Reputation points
2022-10-05T17:23:21.62+00:00

I made an app and for that login and registration is necessary. the code for the registration page is working fine because the data entered in registration page is being showed at the "MICROSOFT SQL SERVER" table.
but when i run the app and login the data with wrong input valued to check if it is working right or not that shouldn't be. it goes to the main page.
I can't figure it out. please help.

THE CODE FOR REGISTRATION PAGE IS::

public partial class signup : Window
{
static SqlConnection con = new SqlConnection(@"Data Source=(localdb)\ProjectModels;Initial Catalog=Youtube;Integrated Security=True");
static SqlCommand scmd;
public signup()
{
InitializeComponent();
}

    private void Button_Click(object sender, RoutedEventArgs e)  
    {  
        MainWindow objMainWindow = new MainWindow();  
        this.Visibility = Visibility.Hidden;  
        objMainWindow.Show();  
    }  



    private void t1_TextChanged(object sender, TextChangedEventArgs e)  
    {  
       
    }  
    /// <summary>  
    /// //  
    /// </summary>  
    /// <param name="sender"></param>  
    /// <param name="e"></param>  
      
    private void Button_Click_2(object sender, RoutedEventArgs e)  
    {  
        if (!Authenticate())  
        {  
            MessageBox.Show("Do not keep any textbook blank!");  
            return;  
        }  
        string query = "INSERT INTO Yusers (username,email,passcode,_name,gender,Dob) VALUES(@USER,@EMAIL,@PASS,@NAME,@GENDER,@DOB)";  
        con.Open();  
        scmd = new SqlCommand(query, con);  
        scmd.Parameters.Add("@USER", SqlDbType.VarChar);  
        scmd.Parameters["@USER"].Value = UserTbox.Text;  

        scmd.Parameters.Add("@EMAIL", SqlDbType.VarChar);  
        scmd.Parameters["@EMAIL"].Value = EmailTbox.Text;  


        scmd.Parameters.Add("@PASS", SqlDbType.VarChar);  
        scmd.Parameters["@PASS"].Value = PassTbox.Text;  

        scmd.Parameters.Add("@NAME", SqlDbType.VarChar);  
        scmd.Parameters["@NAME"].Value = NameTbox.Text;  

        scmd.Parameters.Add("@GENDER", SqlDbType.VarChar);  
        scmd.Parameters["@GENDER"].Value = GenderCbox.Text;  

        scmd.Parameters.Add("@DOB", SqlDbType.VarChar);  
        scmd.Parameters["@DOB"].Value = dateTimePicker1.Text;  

        scmd.ExecuteNonQuery();  
        con.Close();  


        Window1 objWindow1 = new Window1();  
        this.Visibility = Visibility.Hidden;  
        objWindow1.Show();  
    }  
    bool Authenticate()  
    {  
        if (string.IsNullOrWhiteSpace(UserTbox.Text) ||  
            string.IsNullOrWhiteSpace(PassTbox.Text) ||  
            string.IsNullOrWhiteSpace(NameTbox.Text)  
                )  
            return false;  
        else return true;  

    }  

THE CODE FOR LOGIN PAGE::

public partial class Window1 : Window
{
static SqlConnection con = new SqlConnection(@"Data Source=(localdb)\ProjectModels;Initial Catalog=Youtube;Integrated Security=True");
static SqlCommand scmd;
public Window1()
{
InitializeComponent();
}

    private void Previous_Click(object sender, RoutedEventArgs e)  
    {  


        MainWindow objMainWindow = new MainWindow();  
        this.Visibility = Visibility.Hidden;  
        objMainWindow.Show();  
    }  
    //  
    private void Button_Click(object sender, RoutedEventArgs e)  
    {  

        bool isUserok = false, ispassok = false;  

        if (!Authenticate())  
        {  
            MessageBox.Show("Do not keep any textbook blank!");  
            return;  
        }  
          

       string query= "SELECT * FROM Yusers WHERE username=@USER AND passcode=@PASS";  
        con.Open();  

        scmd = new SqlCommand(query, con);  
        scmd.Parameters.Add("@USER", SqlDbType.VarChar);  
        scmd.Parameters["@USER"].Value = UserTbox.Text;  
        scmd.Parameters.Add("@PASS", SqlDbType.VarChar);  
        scmd.Parameters["@PASS"].Value = PassTbox.Text;  

        SqlDataReader sda = scmd.ExecuteReader();  

        if(sda.HasRows)  
        {  
            ispassok = true;  
        }  
        if (isUserok== true) {  
            con.Close();  
        }  
        else if (isUserok == true && ispassok == false)  
        {  

            MessageBox.Show("Wrong password or user doesnn't exist!!!!");  
        }  
        else  
        {  
            Close();  
            TMA objTMA = new TMA();  
            this.Visibility = Visibility.Hidden;  
            objTMA.Show();  
        }  
        con.Close();  
    }  



    bool Authenticate()  
    {  
        if (string.IsNullOrWhiteSpace(UserTbox.Text) ||  
            string.IsNullOrWhiteSpace(PassTbox.Text)   
             
                )  
            return false;  
        else return true;  

    }  

Please help me out.

Windows 10
Windows 10
A Microsoft operating system that runs on personal computers and tablets.
10,618 questions
Windows Presentation Foundation
Windows Presentation Foundation
A part of the .NET Framework that provides a unified programming model for building line-of-business desktop applications on Windows.
2,671 questions
SQL Server
SQL Server
A family of Microsoft relational database management and analysis systems for e-commerce, line-of-business, and data warehousing solutions.
12,714 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,249 questions
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. Bruce (SqlWork.com) 56,026 Reputation points
    2022-10-05T20:29:51.19+00:00

    isUserok is always false, so data entry makes no difference.

    0 comments No comments

  2. Hui Liu-MSFT 38,251 Reputation points Microsoft Vendor
    2022-10-06T07:32:40.853+00:00

    It is recommended that you remove SqlConnection from your code(About your privacy information.). Here is the sample code for the registration login page. You could try to refer to it.

    SqlTable:

    CREATE TABLE [dbo].[Registration] (  
        [Id]        INT           IDENTITY (1, 1) NOT NULL,  
        [FirstName] NCHAR (10)    NULL,  
        [LastName]  NCHAR (10)    NULL,  
        [Email]     NVARCHAR (50) NULL,  
        [Password]  NCHAR (10)    NULL,  
        [Address]   NCHAR (10)    NULL,  
        [RefistrationOnTime] DATETIME NULL,   
         
        PRIMARY KEY CLUSTERED ([Id] ASC)  
    );  
    

    Registration :
    MainWindow.xaml:

    247899-registion8.txt

    MainWindow.xaml.cs:

    using System;  
    using System.Data;  
    using System.Data.SqlClient;  
    using System.Text.RegularExpressions;  
    using System.Windows;  
      
     public partial class MainWindow : Window  
        {  
            public MainWindow()  
            {  
                InitializeComponent();  
            }  
            private void Login_Click(object sender, RoutedEventArgs e)  
            {  
                Login login = new Login();  
                login.Show();  
                Close();  
            }  
            private void button2_Click(object sender, RoutedEventArgs e)  
            {  
                Reset();  
            }  
            public void Reset()  
            {  
                textBoxFirstName.Text = "";  
                textBoxLastName.Text = "";  
                textBoxEmail.Text = "";  
                textBoxAddress.Text = "";  
                passwordBox1.Password = "";  
                passwordBoxConfirm.Password = "";  
            }  
            private void button3_Click(object sender, RoutedEventArgs e)  
            {  
                Close();  
            }  
            private void Submit_Click(object sender, RoutedEventArgs e)  
            {  
                if (textBoxEmail.Text.Length == 0)  
                {  
                    errormessage.Text = "Enter an email.";  
                    textBoxEmail.Focus();  
                }  
                else if (!Regex.IsMatch(textBoxEmail.Text, @"^[a-zA-Z][\w\.-]*[a-zA-Z0-9]@[a-zA-Z0-9][\w\.-]*[a-zA-Z0-9]\.[a-zA-Z][a-zA-Z\.]*[a-zA-Z]$"))  
                {  
                    errormessage.Text = "Enter a valid email.";  
                    textBoxEmail.Select(0, textBoxEmail.Text.Length);  
                    textBoxEmail.Focus();  
                }  
                else  
                {  
                    string firstname = textBoxFirstName.Text;  
                    string lastname = textBoxLastName.Text;  
                    string email = textBoxEmail.Text;  
                    string password = passwordBox1.Password;  
                    if (passwordBox1.Password.Length == 0)  
                    {  
                        errormessage.Text = "Enter password.";  
                        passwordBox1.Focus();  
                    }  
                    else if (passwordBoxConfirm.Password.Length == 0)  
                    {  
                        errormessage.Text = "Enter Confirm password.";  
                        passwordBoxConfirm.Focus();  
                    }  
                    else if (passwordBox1.Password != passwordBoxConfirm.Password)  
                    {  
                        errormessage.Text = "Confirm password must be same as password.";  
                        passwordBoxConfirm.Focus();  
                    }  
                    else  
                    {  
      
                         errormessage.Text = "";  
                    string address = textBoxAddress.Text;  
                    SqlConnection con = new SqlConnection("constr");  
                     con.Open();  
                     
                    string cmdText = string.Format("SELECT ID FROM [dbo].[Registration] Where Email = '{0}' And Password = '{1}'", email, password);  
                    SqlCommand cmd = new SqlCommand(cmdText, con);  
                    object result = cmd.ExecuteScalar();  
                    if (result != null)  
                    {  
                        errormessage.Text = "User existed";  
                        passwordBoxConfirm.Focus();  
                    }  
                    else  
                    {  
                        
                        SqlCommand cmd1 = new SqlCommand("Insert into  [dbo].[Registration] (FirstName,LastName,Email,Password,Address) values('" + firstname + "','" + lastname + "','" + email + "','" + password + "','" + address + "')", con);  
                        cmd1.CommandType = CommandType.Text;  
                        cmd1.ExecuteNonQuery();  
                        errormessage.Text = "You have Registered successfully.";  
                        Reset();  
                    }  
                    con.Close();  
                    }  
                }  
            }  
              
        }  
    

    Login:

    <Grid>  
            <TextBlock Height="23" HorizontalAlignment="Left" Margin="10,10,0,0" Name="LoginHeading" Text="Login:" VerticalAlignment="Top" FontSize="17" FontStretch="ExtraCondensed"/>  
            <TextBlock Height="50" HorizontalAlignment="Left" Margin="24,48,0,0" Name="textBlockHeading" VerticalAlignment="Top" FontSize="12" FontStyle="Italic" Padding="5">    
                Note: Please login here to view the features of this site. If you are new on this site then <LineBreak /><!--line break-->    
                please click on    
                <TextBlock>    
                     <Hyperlink Click="buttonRegister_Click" FontSize="14" FontStyle="Normal">Register</Hyperlink>    
                </TextBlock>    
                button    
            </TextBlock>  
            <TextBlock Height="23" HorizontalAlignment="Left" Margin="66,120,0,0" Name="textBlock1" Text="Email" VerticalAlignment="Top" Width="67" />  
            <TextBlock Height="23" HorizontalAlignment="Left" Margin="58,168,0,0" Name="textBlock2" Text="Password" VerticalAlignment="Top" Width="77" />  
            <TextBox Height="23" HorizontalAlignment="Left" Margin="118,115,0,0" Name="textBoxEmail" VerticalAlignment="Top" Width="247" />  
            <PasswordBox Height="23" HorizontalAlignment="Left" Margin="118,168,0,0" Name="passwordBox1" VerticalAlignment="Top" Width="247" />  
            <Button Content="Login" Height="23" HorizontalAlignment="Left" Margin="118,211,0,0" Name="button1" VerticalAlignment="Top" Width="104" Click="button1_Click" />  
            <TextBlock Height="23" HorizontalAlignment="Left" x:Name ="errormessage" VerticalAlignment="Top" Width="247" Margin="118,253,0,0"  OpacityMask="Crimson" Foreground="#FFE5572C"  />  
        </Grid>  
    

    Login.xaml.cs:

    public partial class Login : Window  
        {  
            public Login()  
            {  
                InitializeComponent();  
            }  
            MainWindow registration = new MainWindow();  
            Welcome welcome = new Welcome();  
            private void button1_Click(object sender, RoutedEventArgs e)  
            {  
                if (textBoxEmail.Text.Length == 0)  
                {  
                    errormessage.Text = "Enter an email.";  
                    textBoxEmail.Focus();  
                }  
                else if (!Regex.IsMatch(textBoxEmail.Text, @"^[a-zA-Z][\w\.-]*[a-zA-Z0-9]@[a-zA-Z0-9][\w\.-]*[a-zA-Z0-9]\.[a-zA-Z][a-zA-Z\.]*[a-zA-Z]$"))  
                {  
                    errormessage.Text = "Enter a valid email.";  
                    textBoxEmail.Select(0, textBoxEmail.Text.Length);  
                    textBoxEmail.Focus();  
                }  
                else  
                {  
                    string email = textBoxEmail.Text;  
                    string password = passwordBox1.Password;  
                    SqlConnection con = new SqlConnection("constr");  
                    con.Open();  
                    SqlCommand cmd = new SqlCommand("Select * from  [dbo].[Registration]  where Email='" + email + "'  and password='" + password + "'", con);  
                    cmd.CommandType = CommandType.Text;  
                    SqlDataAdapter adapter = new SqlDataAdapter();  
                    adapter.SelectCommand = cmd;  
                    DataSet dataSet = new DataSet();  
                    adapter.Fill(dataSet);  
                    if (dataSet.Tables[0].Rows.Count > 0)  
                    {  
                        string username = dataSet.Tables[0].Rows[0]["FirstName"].ToString() + " " + dataSet.Tables[0].Rows[0]["LastName"].ToString();  
                        welcome.TextBlockName.Text = username;  
                        welcome.Show();  
                        Close();  
                    }  
                    else  
                    {  
                        errormessage.Text = "Sorry! Please enter existing emailid/password.";  
                    }  
                    con.Close();  
                }  
            }  
            private void buttonRegister_Click(object sender, RoutedEventArgs e)  
            {  
                registration.Show();  
                Close();  
            }  
        }  
    

    Welcome:

    <Grid>  
            <TextBlock Height="23" HorizontalAlignment="Left" Margin="10,10,0,0" x:Name="WelcomeHeading" Text="Welcome:" VerticalAlignment="Top" FontSize="17" FontStretch="ExtraCondensed"/>  
            <TextBlock Height="23" HorizontalAlignment="Left" Margin="90,10,0,0" x:Name="TextBlockName"  VerticalAlignment="Top" FontSize="15" FontStretch="ExtraCondensed" />  
        </Grid>  
    

    The result:
    248943-image.png
    Login:
    248849-image.png

    ----------------------------------------------------------------------------

    If the response is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.