Click here to Skip to main content
15,791,739 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
i need a code for login button in c#. I HAVE 2 fields username and password and login button and back end as sql server i have created a table my name register it has login and password fields. once i click on login button it should login if the user data is correct of not it should error.

can anyone help with this in writing the code.

What I have tried:

i have tried in connecting to the database to access the existing fields i.e., username and password.
Updated 20-May-21 16:38pm
Mehdi Gholam 17-Sep-16 2:42am    
Your question makes no sense since "login" depends on what you are doing and how you built your system.
Member 12650438 17-Sep-16 3:22am    
my code is not accepting after proving the correct details also.

private void button1_Click_1(object sender, EventArgs e)
string cs = @"Data Source=.;Database=master;Integrated Security=True;";

if (textBox1.Text == "" || textBox2.Text == "")
MessageBox.Show("Please provide UserName and Password");
//Create SqlConnection
SqlConnection con = new SqlConnection(cs);
SqlCommand cmd = new SqlCommand("Select * from Register where UserNmae=@username and Password=@password", con);
cmd.Parameters.AddWithValue("@username", textBox1.Text);
cmd.Parameters.AddWithValue("@password", textBox2.Text);
SqlDataAdapter adapt = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
int count = ds.Tables[0].Rows.Count;
//If count is equal to 1, than show frmMain form
if (count == 1)
MessageBox.Show("Login Successful!");
Dashboard dsb = new Dashboard();
MessageBox.Show("Login Failed!");
catch (Exception ex)
Patrice T 17-Sep-16 9:19am    
Use Improve question to update your question.
So that everyone can pay attention to this information.
OriginalGriff 17-Sep-16 3:40am    
And? What happens that you don't expect, or does happen that you didn't?
BillWoodruff 17-Sep-16 4:52am    
What is the exception text that appears in the MessageBox when it fails ?

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900