DJ Morand DJ Morand - 20 days ago 6
C# Question

C# Login Form, Login Button Doesn't Respond

So, I'm new to VS and C#, I'm self-teaching to get a better understanding of the backend of the product I work with. I created a small database with some information and a Login form. Everything appears to compile correctly, but the login button doesn't respond when clicked, neither does the cancel button for that matter. Not sure what I am missing, code is below:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace CorpLogin
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
//DB Connection String
string cs = @"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\CORPORATION.mdf;" +
"Integrated Security=True";

//Login Button clicked
private void LoginButton1_Click(object sender, EventArgs e)
{
//Validates text entered
if (userNameText1.Text == "")
{
MessageBox.Show("USERNAME and PASSWORD are required fields.");
return;
}
if (passwordText1.Text == "")
{
MessageBox.Show("USERNAME and PASSWORD are required fields.");
return;
}

try
{
//Connect to SQL
SqlConnection con = new SqlConnection(cs);
con.Open();
SqlCommand cmd = new SqlCommand("select * from USERS where USERNAME=@username" +
"and PASSWORD=@password", con);
cmd.Parameters.AddWithValue("@username", userNameText1.Text);
cmd.Parameters.AddWithValue("@password", passwordText1.Text);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
con.Close();
int count = ds.Tables[0].Rows.Count;

//Show new form or fail message
if (count == 1)
{
this.Hide();
CorpView cv = new CorpView();
cv.Show();
}
else
{
MessageBox.Show("ACCESS DENIED");
}
}
//Catch program exceptions
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
//Cancel Button Clicked
private void CancelButton1_Click(object sender, EventArgs e)
{
Application.Exit();
}
}
}


Any help is appreciated. Thanks.

Answer

You also have to add the event handler Registration.

This can be done in the designer by double-click the button, or manually in your form:

LoginButton1.Click += new System.EventHandler(LoginButton1_Click);