How would i use a database as a reference for logging in

login using C#

  • (2 Pages)
  • +
  • 1
  • 2

17 Replies - 1592 Views - Last Post: 06 May 2010 - 03:28 PM Rate Topic: -----

#1 Guest_C#novice*


Reputation:

How would i use a database as a reference for logging in

Posted 03 May 2010 - 10:58 AM

hey i am now starting out with using C# but i have previous experience with C++. I would like someone to tell me how i would login using a database. I think i understand it a little using a console app but i am at a lost when it comes to incorporating it into a Form.this was the code i used in the console app :
       static void Main(string[] args)
        {
            string connectionstring = @"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Accountinfo.mdf;Integrated Security=True;User Instance=True";
                SqlConnection connection = new SqlConnection(connectionstring);
try {  connection.Open();
       Console.WriteLine("Connected");
       Console.WriteLine(" ");
                }
catch (Exception e) {Console.WriteLine(e);
                    Console.Read(); }

Console.Write(" Username> ");
            string Login_ID = Console.ReadLine();
            Console.Write("Password> ") ;
            string Password = Console.ReadLine();
SqlCommand command = new SqlCommand("SELECT * FROM (Login_ID) WHERE Login_ID='" + Login_ID + "' AND Password='" + Password + "'",connection);
            SqlDataReader reader = null;
            reader = command.ExecuteReader();
            while (reader.Read() )
            {
                Console.WriteLine("WelCome " + reader["Login_ID"].ToString());
                   Console.Read();
            }
            
 }}
 


i dont want anyone to do it for me but if you have the code alredy, i wouldn't mind looking at it or you helping me. What i want is a link/source that i can see how to do this using Visual C# 2008 express edition or a layout on how i would go about doing this. thanks

Is This A Good Question/Topic? 0

Replies To: How would i use a database as a reference for logging in

#2 PsychoCoder  Icon User is offline

  • Google.Sucks.Init(true);
  • member icon

Reputation: 1659
  • View blog
  • Posts: 19,853
  • Joined: 26-July 07

Re: How would i use a database as a reference for logging in

Posted 03 May 2010 - 11:02 AM

It's the same for console as it is for WinForms applications. Is your above code generating any errors?
Was This Post Helpful? 0
  • +
  • -

#3 Guest_C#novice*


Reputation:

Re: How would i use a database as a reference for logging in

Posted 03 May 2010 - 11:07 AM

View PostPsychoCoder, on 03 May 2010 - 10:02 AM, said:

It's the same for console as it is for WinForms applications. Is your above code generating any errors?

Was This Post Helpful? 0

#4 Guest_C#novice*


Reputation:

Re: How would i use a database as a reference for logging in

Posted 03 May 2010 - 11:08 AM

sorry about that no it didnt generate any errors
Was This Post Helpful? 0

#5 Guest_C#novice*


Reputation:

Re: How would i use a database as a reference for logging in

Posted 03 May 2010 - 11:11 AM

so wouldnt i have to edit the code since it is in a form app instead of a console app?
Was This Post Helpful? 0

#6 Guest_C#novice*


Reputation:

Re: How would i use a database as a reference for logging in

Posted 03 May 2010 - 11:20 AM

so this code
 string connectionstring = @"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\LNP.mdf;Integrated Security=True;User Instance=True";
                SqlConnection connection = new SqlConnection(connectionstring);

                try {
                    connection.Open();
                    Console.WriteLine("Connected");
                    Console.WriteLine(" ");
                }
                catch (Exception e) {
                    Console.WriteLine(e);
                    Console.Read();
                } 

would remain the same then?
Was This Post Helpful? 0

#7 Dannyboy997  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 64
  • View blog
  • Posts: 258
  • Joined: 17-April 09

Re: How would i use a database as a reference for logging in

Posted 03 May 2010 - 07:33 PM

Other than the
Console.WriteLine();


You can't Call the Console If it's a Form Application.

You can Call the
MessageBox.Show();
Instead.

Or you can place an empty label then just call that label:

this.labelnamehere.Text = "";
This will access the Text property or value of the label.

Hope This Helps!
Was This Post Helpful? 1
  • +
  • -

#8 MentalFloss  Icon User is offline

  • .
  • member icon

Reputation: 577
  • View blog
  • Posts: 1,500
  • Joined: 02-September 09

Re: How would i use a database as a reference for logging in

Posted 03 May 2010 - 07:46 PM

What I like to do with my applications is to create a windows form project and then go into the project properties via right-click -> Properties.

Then, change the Output type to Console Application.

This will cause a console window to also pop up in conjunction with your form application. This way you can print out messages into the console window as well as work through the form.

When you're ready to remove the console pop-up, set the output type back to Windows application.

With all those Console.WriteLine calls, you can still view them if you execute your application and then open up your task manager. Go to the process of your application and right-click -> Debug. When the debug IDE comes up, there will be a "Output" window. It will show all of those Console.Write messages.

To the point of your actual question, others already answered it. This reply is just gravy.

Hope this helps. Take care.
Was This Post Helpful? 1
  • +
  • -

#9 GhoSt1090  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 21
  • Joined: 03-May 10

Re: How would i use a database as a reference for logging in

Posted 04 May 2010 - 11:50 AM

View PostDannyboy997, on 03 May 2010 - 06:33 PM, said:

Other than the
Console.WriteLine();


You can't Call the Console If it's a Form Application.

You can Call the
MessageBox.Show();
Instead.

Or you can place an empty label then just call that label:

this.labelnamehere.Text = "";
This will access the Text property or value of the label.

Hope This Helps!


Should i change the [code]Console.read(;)[code] also? or leave it?
Was This Post Helpful? 0
  • +
  • -

#10 Dannyboy997  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 64
  • View blog
  • Posts: 258
  • Joined: 17-April 09

Re: How would i use a database as a reference for logging in

Posted 04 May 2010 - 03:05 PM

Yes You Should Change it.

If your going with a visual application or an interface you cannot have anything related to Console

e.g:

Console.WriteLine();


Instead you could make a text box and get the user to type the input into there.

to read it you just have to do the following:
TextBoxName.Text;//This is what they typed in.



You should also put a button, then when they click on that button you can continue your application.


When your editing the visual part of the application. Double click on the button. Your then presented within a function inside the code editor. To Alert what they wrote:

MessageBox.Show(TextBoxName.Text);//This is within that function I was taking about...




And it will alert with the data they typed.


Hope This Helps!

If it didn't work please post a reply.

This post has been edited by Dannyboy997: 04 May 2010 - 03:06 PM

Was This Post Helpful? 0
  • +
  • -

#11 GhoSt1090  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 21
  • Joined: 03-May 10

Re: How would i use a database as a reference for logging in

Posted 04 May 2010 - 04:03 PM

View PostDannyboy997, on 04 May 2010 - 02:05 PM, said:

Yes You Should Change it.

If your going with a visual application or an interface you cannot have anything related to Console

e.g:

Console.WriteLine();


Instead you could make a text box and get the user to type the input into there.

to read it you just have to do the following:
TextBoxName.Text;//This is what they typed in.



You should also put a button, then when they click on that button you can continue your application.


When your editing the visual part of the application. Double click on the button. Your then presented within a function inside the code editor. To Alert what they wrote:

MessageBox.Show(TextBoxName.Text);//This is within that function I was taking about...




And it will alert with the data they typed.


Hope This Helps!

If it didn't work please post a reply.


ye what you said makes sense but i dont know what to do with the [code] Console.Read(); [code]

i changed one of the Console.Writeline to [code] MessageBox.Show(ex.Message + Environment.NewLine + Environment.NewLine + ex.StackTrace);[code]
but the problem i have is changing the Console.Read to something else.. but the thing is, i dont know what i could change it to

This post has been edited by GhoSt1090: 04 May 2010 - 04:58 PM

Was This Post Helpful? 0
  • +
  • -

#12 Dannyboy997  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 64
  • View blog
  • Posts: 258
  • Joined: 17-April 09

Re: How would i use a database as a reference for logging in

Posted 04 May 2010 - 04:19 PM

You won't Need
Console.Read


Because What this is, is it let's the user read the information given.

It just pauses the Application Until the User does something, but because this is not a Console Application you don't need that.

Your Application will stay open unless the user exits it.


Hope This Helps!


NOTE: Please Fix your Code Tags: Your missing a closing '/' on the second [code] tag.
Was This Post Helpful? 1
  • +
  • -

#13 GhoSt1090  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 21
  • Joined: 03-May 10

Re: How would i use a database as a reference for logging in

Posted 04 May 2010 - 05:05 PM

tell me if my code is supposed to look like this when i am finished.
string connectionstring = @"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\LOG.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True";
            SqlConnection connection = new SqlConnection(connectionstring);

            try{connection.Open();}
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message + Environment.NewLine + Environment.NewLine + ex.StackTrace);
                        MessageBox.Show(textBox1.Text);
                    }
                if (radioButton1.Checked)
                {
                   

                    SqlCommand command = new SqlCommand("SELECT * FROM [LOGINtbl] WHERE User ='" + User + "' AND Password='" + Password + "'", connection);
                    SqlDataReader reader = null;
                    reader = command.ExecuteReader();

                   if(reader.Read())
                    {
                       MessageBox.Show("Welcome", "Login successful");
                            
                            Form2 myForm2 = new Form2(); myForm2.Show();
                           
                    }
                      MessageBox.Show("Please enter the correct Login ID/ password");
                       textBox2.Clear();
                }

else if (radioButton2.Checked)
                {
                    SqlCommand command = new SqlCommand("SELECT * FROM [Cashiertable] WHERE User ='" + User + "' AND Password='" + Password + "'", connection);
                    SqlDataReader reader = null;
                    reader = command.ExecuteReader();

                    while (reader.Read())
                    {
                        Form3 myForm3 = new Form3(); myForm3.Show();
                       
                        MessageBox.Show("Welcome", "Login successful");

                    }                 
                   
                    MessageBox.Show("Please enter the correct Login ID/ password");
                    textBox2.Clear();
                }

This post has been edited by GhoSt1090: 04 May 2010 - 05:32 PM

Was This Post Helpful? 0
  • +
  • -

#14 Dannyboy997  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 64
  • View blog
  • Posts: 258
  • Joined: 17-April 09

Re: How would i use a database as a reference for logging in

Posted 04 May 2010 - 05:12 PM

Again Please Fix your Code Tag:

[ code ]CODE IN HERE:[ /code]

Check the ending code tag.

This post has been edited by Dannyboy997: 04 May 2010 - 05:12 PM

Was This Post Helpful? 0
  • +
  • -

#15 MentalFloss  Icon User is offline

  • .
  • member icon

Reputation: 577
  • View blog
  • Posts: 1,500
  • Joined: 02-September 09

Re: How would i use a database as a reference for logging in

Posted 05 May 2010 - 10:18 AM

There are several things you can change about this.

First, let's address the query method. Since you are attempting to get a matching record based on provided user input on login and password, it's better to get the row count back.

So, ditch the SqlDataReader entirely and change the command execution to ExecuteScalar().

int result = (int)command.ExecuteScalar();
if (result > 0)
{
    // login is successful because a row was returned.
}



Now, in order to do that, we have to change the query to be an aggregate query:

SELECT COUNT(*) FROM [LOGINtbl] WHERE User ='" + User + "' AND Password='" + Password + "'"



Next, let's parameterize the query so it can be just one single string:

string query = "SELECT COUNT(*) FROM [LOGINtbl] WHERE User = @UserName AND Password = @Password";



In order to parameterize queries, you have to add the parameter by name to the Parameters collection on the command object. This should clear it up:

command.Parameters.AddWithValue("@UserName", User);
command.Parameters.AddWithValue("@Password", Password);



Alright. Next, SqlConnection implements IDisposable so we are able to use the "using" construct so it will dispose for us:

using (SqlConnection connection = new SqlConnection(connectionString))
{
    // code goes here.
}



Also, you want to make a new class that is not dependent on the form. Since the logic depends on the settings of radiobutton1 and radiobutton2 and I don't know what they represent, I'll just ignore them, but you'll want to pass them in as boolean values to whatever needs them in this helper class.

Let's put all these concepts together, shall we?

public class DatabaseLogin
{
    private string connectString;
    public DatabaseLogin(string connectionString)
    {
         connectString = connectionString;
    }

    public bool IsLoginSuccessful(string user, string password)
    {
        // Here is our query set up for parameterization later:
        string query = "SELECT COUNT(*) FROM [LOGINtbl] WHERE User = @UserName AND Password = @Password";
        
        // This will be the number of records returned and ultimately our return condition from this method:
        int result = 0;

        // These both implement IDisposable so we can use our "using" statement with them:
        using (SqlConnection connection = new SqlConnection(connectString))
        using (SqlCommand command = new SqlCommand(query, connection))
        {
            try
            {
                 // Add our parameters to the command object:
                 command.Parameters.AddWithValue("@UserName", user);
                 command.Parameters.AddWithValue("@Password", password);

                 // Open the connection:
                 connection.Open();

                 // Do the actual work:
                 int result = (int)command.ExecuteScalar();
            }
            catch (SqlException sqlEx)
            {
                // handle your errors here. Maybe just return false?
            }
        }

        // All that's left is to return whether result is greater than zero or not:
        return (result > 0);
    }
}



Hope this helps out a bit.

This post has been edited by MentalFloss: 05 May 2010 - 10:20 AM

Was This Post Helpful? 0
  • +
  • -

  • (2 Pages)
  • +
  • 1
  • 2