Some comments:
If the password field is empty, why compel the user to retype the user? just set the cursor focus to the password field ... txtPass.Focus();
Equally for the opposite situation.
To check if a string
is empty, I use String.IsNullOrEmpty(txtPass.Text);
Just below where you open the connection, you declare two variables:
string user = txtUser.Text;
string pass = txtPass.Text;
but do not use them at all.
And at the time of executing the SQL command, use parameters, and do not concatenate string
in this way. The way SQL injection is is very easy.
I made a very simple code of how would a login screen in your case:
The main Application Form (which opens in the Main
method with Application.Run
) should be its main form, not the login form. So I put the login dialog and if the result is OK, I continue with the application and open FormPrincipal
, in your case Form1 or FormGeral.
Program:
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
FormLogin formLogin = new FormLogin();
if (formLogin.ShowDialog() == DialogResult.OK)
{
Application.Run(new FormPrincipal(formLogin.UsuarioLogado));
}
}
}
FormLogin:
This would be the code for FormLogin
:
public partial class FormLogin : Form
{
public Usuarios UsuarioLogado { get; set; }
public FormLogin()
{
InitializeComponent();
//O botão cancela, retorna 'Cancel'
buttonCancela.DialogResult = System.Windows.Forms.DialogResult.Cancel;
}
//Botão Login ou OK
private void buttonLogin_Click(object sender, EventArgs e)
{
try
{
if (!String.IsNullOrEmpty(txtUser.Text))
{
if (!String.IsNullOrEmpty(txtPass.Text))
{
//A rotina que valida o login do usuário, está dentro da
//classe Usuarios, e se for válido, retorna um objeto do
//tipo Usuarios, caso contrário, retorna null
UsuarioLogado = Usuarios.ValidarLogin(txtUser.Text, txtPass.Text);
if (UsuarioLogado != null)
{
//Se retornou o usuário, ou seja: é válido, retorna OK
this.DialogResult = System.Windows.Forms.DialogResult.OK;
}
else
{
txtUser.Text = txtPass.Text = "";
labelStatus.Text = "Usuario / Senha inválido";
}
}
else
{
labelStatus.Text = "Informe a senha do usuário";
txtPass.Focus();
}
}
else
{
labelStatus.Text = "Informe o nome de usuário";
txtUser.Focus();
}
}
catch (Exception ex)
{
labelStatus.Text = ex.Message;
}
}
}
Users:
This would be a class of users, here are user properties, and Insert / Update / Delete methods, in addition to the validate login method that is used in FormLogin
public class Usuarios
{
public string Usuario { get; set; }
public string Senha { get; set; }
public string Nome { get; set; }
//Quaisquer outras propriedades
public static Usuarios ValidarLogin(string _user, string _senha)
{
SqlConnection con = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename='C:\Users\TutoDS\Desktop\Trabalho Programação - VideoClub\VideoClub\VideoClub\bdVideoClub.mdf';Integrated Security=True;Connect Timeout=30");
con.Open();
SqlCommand cmd = new SqlCommand("SELECT * FROM Login WHERE User= @usuario AND Pass = @senha;", con);
cmd.Parameters.Add(new SqlParameter("@usuario", _user));
cmd.Parameters.Add(new SqlParameter("@senha", _senha));
SqlDataReader reader = cmd.ExecuteReader();
if (reader.Read())
{
Usuarios obj = new Usuarios();
obj.Nome = reader["coluna_nome"].ToString();
obj.Usuario = reader["User"].ToString();
return obj;
}
else
return null;
}
}
FormPrincipal:
In FormPrincipal, in your constructor, I put a parameter of type Users that will be the user logged into the application, from there you can have which user is using the system.
public partial class FormPrincipal : Form
{
public FormPrincipal(Usuarios _usuarioLogado)
{
InitializeComponent();
labelUsuario.Text = _usuarioLogado.Nome;
}
}
I tried not to extend much, if any other members have suggestions are comfortable. Any questions available.
I've made changes to your code, regardless of my observations, and object-oriented concepts:
SqlConnection sqlCon = null; //Conexão começa em Null
private string strCmd = @"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename='C:\Users\TutoDS\Desktop\VideoClub\VideoClub\VideoClub\bdVideoClub.mdf';Integrated Security=True"; //Conection String da BD
private string strSQL = string.Empty;
public bool logado = false;
public void Sign_in()
{
if (!String.IsNullOrEmpty(txtUser.Text))
{
if (!String.IsNullOrEmpty(txtPass.Text))
{
string usuarioLogado =null;
try
{
sqlCon = new SqlConnection(strCmd);
strSQL = "SELECT Nome FROM [Login] WHERE [User] = @utilizador AND [Pass] = @password";
sqlCon.Open();
SqlCommand cmd = new SqlCommand(strSQL, con);
cmd.Parameters.Add(new SqlParameter("@utilizador", txtUser.Text));
cmd.Parameters.Add(new SqlParameter("@password", txtPass.Text));
SqlDataReader reader = cmd.ExecuteReader();
if (reader.Read())
{
//usuário é válido e o nome está na variável usuarioLogado
logado = true;
usuarioLogado = reader["Nome"].ToString();
}
else
{
//usuário não é válido
txtUser.Text = txtPass.Text = "";
labelStatus.Text = "Usuario / Senha inválido";
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
else
{
labelStatus.Text = "Informe a senha do usuário";
txtPass.Focus();
}
}
else
{
labelStatus.Text = "Informe o nome de usuário";
txtUser.Focus();
}
}