Problem with parameters in Sqlcommand

Asked

Viewed 220 times

0

I am developing a service registration, the first screen is the login and I need to take the position of the user who logged in and indicate a form for it, my code ta thus:

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 PesadaoFinal
{
    public partial class frmLogin : Form
    {

        SqlConnection conn = null;
        private string conexao = @"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\Breno\Documents\Visual Studio 2013\Projects\PesadaoFinal\PesadaoFinal\bd\pesadao_db.mdf;Integrated Security=True;Connect Timeout=30";
        private string consulta = string.Empty;

        public frmLogin()
        {
            InitializeComponent();
        }
        public void logar(){


            conn= new SqlConnection(conexao);

            try{
                string usuario, senha, cargo;

                usuario = txtUsu.Text;
                senha=txtSenha.Text;
                SqlDataReader verCargo = null;


                if(usuario==string.Empty && senha==string.Empty){

                    MessageBox.Show("Usuário e senha devem ser digitados!");
                }
                else if (usuario != null && senha != null)
                {
                    consulta = @"SELECT COUNT(cpf) FROM funcionarios WHERE login = @usuario AND senha = @senha";
                    SqlCommand novoLogin = new SqlCommand(consulta, conn);
                    novoLogin.Parameters.Add(@usuario, SqlDbType.VarChar).Value = usuario;
                    novoLogin.Parameters.Add(@senha, SqlDbType.VarChar).Value = senha;

                    conn.Open();


                    int rs = (int)novoLogin.ExecuteScalar();
                    if (rs > 0)
                    {
                        verCargo = novoLogin.ExecuteReader();
                        cargo = verCargo[7].ToString();
                        if (cargo == "funcionario")
                        {
                            formFunc novoForm = new formFunc();
                            this.Dispose();

                        } if (cargo == "diretor")
                        {
                            frmDiretor novoForm = new frmDiretor();
                            this.Dispose();

                        } if (cargo == "TI")
                        {
                            formTI novoForm = new formTI();
                            this.Dispose();


                        }
                        else
                        {
                            MessageBox.Show("Usuário ou Senha inválidos!");
                        }
                    }

                }


            }catch(SqlException erroBD){
                MessageBox.Show(erroBD +"Erro no banco");

            }


        }
        private void frmLogin_Load(object sender, EventArgs e)
        {


        }

        private void btnLogar_Click(object sender, EventArgs e)
        {
            logar();
        }
    }
}

and the error message you’re giving is this:

imagem de erro ao rodar e tentar logar

  • You can put in your question code examples of what you have so far?

  • will be only two types of form? I did not understand very well, you could describe how should be the result?

  • Gypsy, I erased all my code to start over, I was having a lot of problems. Jovita, would be basically 3 types of Forms, 1 that would allow the "director" register and delete users and do everything else, another that would be for the employee register the services and another pro "technical", inform the bank path, when there was some change.

  • 1

    I rephrased my question and gave real examples.

1 answer

1


Probably your problem is here:

novoLogin.Parameters.Add(@usuario, SqlDbType.VarChar).Value = usuario;
novoLogin.Parameters.Add(@senha, SqlDbType.VarChar).Value = senha;

You should use the double quotes:

novoLogin.Parameters.Add("@usuario", SqlDbType.VarChar).Value = usuario;
novoLogin.Parameters.Add("@senha", SqlDbType.VarChar).Value = senha;

The way you had done, you were passing the contents of the variables usuario and senha as parameter names and not @usuario and @senha as you had defined. You can understand a little more of @ in this question Which means the "@" sign on C#?.

Looking at the continuation of your code, I believe you will have one more problem

int rs = (int)novoLogin.ExecuteScalar();
if (rs > 0)
{
    verCargo = novoLogin.ExecuteReader();
    cargo = verCargo[7].ToString(); \\ <<--------- aqui

In the select that you did in the novoLogin only has a column, and you try to access column 7, probably you will have to adjust the CommandText of novoLogin to make it work.

Another point would be the fact that you’re not exhibiting the Form servant:

frmDiretor novoForm = new frmDiretor();
novoForm.Show(); // ou dependendo de como você fizer novoForm.ShowDialog();
this.Dispose();

You could also use if and some else if instead of just using if to check the positions.

  • Matthew, my code now on the Executereader part is like this, however, it returns nothing and error. Object rs = newLogin.Executescalar(); if (rs== null) , ! Messagebox.Show("Incorrect User or Password"); } Else { &#xA;verCargo = novoLogin.ExecuteReader(CommandBehavior.CloseConnection); &#xA;if (verCargo != null)&#xA;{ &#xA;while (verCargo.Read()) &#xA;&#xA; { &#xA;usulogado=(verCargo[].ToString); &#xA;cpf = (verCargo[].ToString); &#xA;} I have tried to pass verCargo[1], [2], by column name and nothing will.

  • 1

    @brenoguto, I believe that in this case it would be correct to create a new question with this specific problem, because it is already something else and not more what you asked originally. If you consider that my answer helped you, you can accept it if you don’t know how to do it you can take a look at [tour]

Browser other questions tagged

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