Some remarks:
If the password field is empty, why force the user to type the user again? just set the cursor focus to the password field... txtPass.Focus();
Also for the opposite situation.
To check whether 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 uses them for nothing.
And when executing the SQL command, use parameters, and do not concatenate the string
this way. The way it is an SQL Injection is very easy.
I made a very simple code of how to make a login screen in your case:
The main application form (what opens in the method Main
with Application.Run
) should be your 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 the FormPrincipal
, in your case the Form1 or Formgeneral.
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:
That would be the code of 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 the user properties, and Insert / Update / Delete methods, plus the login validation 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 the type Users that will be the user logged in to 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 too much, if any other member has suggestions please feel free. Any questions, available.
I made the changes to your code, not taking into account the observations I gave you, and object orientation 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();
}
}
Try to explain your problem better, there is no way to understand what you need this way. By the way, you do not need to write "help" in the title.
– Jéf Bueno
Apparently it is a Windows Forms application. Is giving some error?
– Leonel Sanches da Silva
Which error gives ? place break points and check at runtime what happens...
– Rovann Linhalis
can start by taking out that last if Else, which Zera the fields if both are filled in...
– Rovann Linhalis