Display logged-in user on C#

Asked

Viewed 1,550 times

1

I was able to get the user logged in through the text typed in TextBox.
But I don’t want the user, I want the username.
Example database:

id = 1
nome_usuario = Administrador
usuario = admin
senha = 1234
nivel_acesso = 1

I want to take the dice nome_usuario and display in a Label in the main form of my application.

That’s my form code frmLogin

public partial class frmLogin : Form
{

    public bool logado = false;
    public static string usuarioConectado;

    public frmLogin()
    {
        InitializeComponent();
    }

    private void btnEntrar_Click(object sender, EventArgs e)
    {
        string conexao = "Data Source=DESKTOP-AJLR3DB\\SQLEXPRESS;Initial Catalog=DBGestor;Integrated Security=True";
        SqlConnection conn = new SqlConnection(conexao);
        SqlCommand comando = new SqlCommand("SELECT * FROM funcionarios WHERE usuario = @usuario and senha = @senha", conn);

        comando.Parameters.Add("@usuario", SqlDbType.NVarChar).Value = txtUsuario.Text;
        comando.Parameters.Add("@senha", SqlDbType.Int).Value = txtSenha.Text;

        conn.Open();

        int i = (int)comando.ExecuteScalar();

        if (i > 0)
        {
            logado = true;
            usuarioConectado = reader["nome_funcionario"].ToString();
            this.Dispose();
        }
        else
        {
            logado = false;
            MessageBox.Show("Usuário e/ou Senha inválido.");
        }
        conn.Close();
    }

    private void txtSenha_KeyPress(object sender, KeyPressEventArgs e)
    {
        if (!Char.IsDigit(e.KeyChar) && e.KeyChar != (char)8)
        {
            e.Handled = true;
            MessageBox.Show("Este campo aceita apenas números.");
        }
    }

    private void btnCancelar_Click(object sender, EventArgs e)
    {
        this.Close();
    }
}

I need to know how to assign the value nome_usuario the variable usuarioConectado
That’s my form code frmPricipal

private void frmPrincipal_Load(object sender, EventArgs e)
{
    lblUsuario.Text = "Olá, " + frmLogin.usuarioConectado;
}

I managed to solve the problem, updated code.

1 answer

2


To read values, you can use the ExecuteReader, see how it would look(follow the comments):

var conn = new SqlConnection(conexao);
var comando = new SqlCommand("SELECT * FROM funcionarios WHERE usuario = @usuario and senha = @senha", conn);

comando.Parameters.Add("@usuario", SqlDbType.NVarChar).Value = txtUsuario.Text;
comando.Parameters.Add("@senha", SqlDbType.Int).Value = txtSenha.Text;

conn.Open();

var reader = comando.ExecuteReader(); //Executa o comando

if (reader.Read()) //Lê uma linha (false se não tiver linhas para ler)
{
    logado = true;
    usuarioConectado = reader["nome_usuario"].ToString(); //Pega o valor de "nome_usuario" da linha que foi lida
    this.Dispose();
}
else
{
    logado = false;
    MessageBox.Show("Usuário e/ou Senha inválido.");
}
conn.Close();

To mess with database, always prefer to use the using.

  • It is returning the following error Não é possível converter implicitamente tipo "object" em "string". Existe uma conversão explícita (há uma conversão ausente?

  • @Giovani Lacked the Tostring. I edited the answer, try to group.

  • I compile the application, type user and password, gives this error System.IndexOutOfRangeException: 'nome_usuario'.

  • I managed to solve the problem, in the SqlCommand is SELECT COUNT(*), just put SELECT * and it worked. Thanks for your attention

Browser other questions tagged

You are not signed in. Login or sign up in order to post.