Executereader how to fill in the fields by searching

Asked

Viewed 102 times

1

I’m having a problem understanding how to return the values within windows form (fill the textbox, etc).

This method executes the Reader data but I don’t know how I can use it to fill in the fields.

public bool BuscarCliente(int id)
{
    using (conn = new NpgsqlConnection(ConnString))
    {
        conn.Open();
        string cmdBuscar = String.Format("SELECT * FROM CLIENTES WHERE ID=@ID");

        using (NpgsqlCommand cmd = new NpgsqlCommand(cmdBuscar, conn))
        {
            cmd.Parameters.Add(new NpgsqlParameter("@ID", id));

            NpgsqlDataReader reader =  cmd.ExecuteReader();

            if (reader.Read())
            {
                //campos

            }
            else
            {
                //erro
            }
        }
    }
}

I saw in some topics the staff uses this way:

Example: txtBairro.Text = reader[0].ToString(); But in this case he used inside the button and in my case is in a class.

How do I do that?

Class:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Npgsql;
using System.Collections;

namespace GE
{
    class FDP
    {
        static string serverName = "localhost";
        static string port = "5432";
        static string userName = "postgres";
        static string password = "adm";
        static string databaseName = "GE";
        NpgsqlConnection conn = null;
        string ConnString = null;

        public FDP()
        {
            ConnString = String.Format("Server={0};Port={1};User Id={2};Password={3};Database={4};",
                                       serverName, port, userName, password, databaseName);

        }

        public bool InserirCliente(ArrayList p_arr)
        {
            using (conn = new NpgsqlConnection(ConnString))
            {
                conn.Open();
                string cmdInserir = String.Format("INSERT INTO CLIENTES (NOME, ENDERECO, CIDADE, EMAIL, TELEFONE) VALUES (@NOME, @ENDERECO, @CIDADE, @EMAIL, @TELEFONE)");

                try
                {
                    using (NpgsqlCommand cmd = new NpgsqlCommand(cmdInserir, conn))
                    {
                        cmd.Parameters.Add(new NpgsqlParameter("@NOME", p_arr[0]));
                        cmd.Parameters.Add(new NpgsqlParameter("@ENDERECO", p_arr[1]));
                        cmd.Parameters.Add(new NpgsqlParameter("@CIDADE", p_arr[2]));
                        cmd.Parameters.Add(new NpgsqlParameter("@EMAIL", p_arr[3]));
                        cmd.Parameters.Add(new NpgsqlParameter("@TELEFONE", p_arr[4]));

                        cmd.ExecuteNonQuery();
                        return true;
                    }
                }catch (NpgsqlException ex)
                {
                    throw ex;
                }
                finally
                {
                    conn.Close();
                }
             }
         }

        public int UltimoRegistroCliente()
        {
            using (conn = new NpgsqlConnection(ConnString))
            {
                conn.Open();
                string cmdLast = String.Format("SELECT * FROM CLIENTES ORDER BY ID_CLIENTE DESC LIMIT 1;");

                using (NpgsqlCommand cmd = new NpgsqlCommand(cmdLast, conn))
                {
                    return Convert.ToInt32(cmd.ExecuteScalar());   
                }

            }
        }

        public bool BuscarCliente(int id)
        {
            using (conn = new NpgsqlConnection(ConnString))
            {
                conn.Open();
                string cmdBuscar = String.Format("SELECT * FROM CLIENTES WHERE ID=@ID");

                using (NpgsqlCommand cmd = new NpgsqlCommand(cmdBuscar, conn))
                {
                    cmd.Parameters.Add(new NpgsqlParameter("@ID", id));

                    NpgsqlDataReader reader =  cmd.ExecuteReader();

                    if (reader.Read())
                    {
                        //campos

                    }
                    else
                    {
                        //erro
                    }
                }
            }
        } 

        public bool DeletarCliente(int id)
        {
            using (conn = new NpgsqlConnection(ConnString))
            {
                conn.Open();
                string cmdDeletar = String.Format("DELETE FROM CLIENTES WHERE ID_CLIENTE=@ID");

                using (NpgsqlCommand cmd = new NpgsqlCommand(cmdDeletar, conn))
                {
                    cmd.Parameters.Add(new NpgsqlParameter("@ID", id));

                    cmd.ExecuteNonQuery();
                    return true;
                }
            }
        }
    }
 }
  • Create properties in your class and pass the values to it, in your form you create an instance of your class and call the method BuscarCliente, after that you take the content of its properties and play for the textbox

  • @Robertodecampos guy did not understand very well, if you can answer in a more practical way, Gradeco

1 answer

3


Without going too deep, just take the columns of the dataReader:

public bool BuscarCliente(int id)
{
    bool retorno = false;
    using (conn = new NpgsqlConnection(ConnString))
    {
        conn.Open();

        string cmdBuscar = String.Format("SELECT * FROM CLIENTES WHERE ID=@ID");

        using (NpgsqlCommand cmd = new NpgsqlCommand(cmdBuscar, conn))
        {
            cmd.Parameters.Add(new NpgsqlParameter("@ID", id));

            NpgsqlDataReader reader =  cmd.ExecuteReader();

            if (reader.Read())
            {
                this.Nome = reader[0].ToString(); //onde 0 é índice da coluna do resultado da Query
                //ou
                this.Nome = reader["coluna_nome"].ToString();

               ... outros campos...

              retorno = true;
            }
        }
        conn.Close();
    }

    return retorno;
}

There at the button event, so I understand from your code you will do the following:

    Cliente objCliente;
    private void buttonBuscarCliente_Click(object sender, EventArgs e)
    {
           objCliente = new Cliente();
           if (objCliente.BuscarCliente(1)) //onde 1 é o código que será buscado. Aqui você deve colocar o campo de busca, com uma conversão de string para inteiro
           {
               //Buscou o cliente com sucesso
               textBoxNome.Text = objCliente.Nome;
           }
           else
           {
             //Erro ao buscar cliente
             textBoxNome.Text = "";
           }
    }

BS.: I have not done any error handling.

  • This part of getting the column I understood, I want to know when I use the class there in the search button as it fills the fields

  • If you can change the question to make it clearer, but that’s exactly what I needed

  • That one this.Nome that name is what? I need to declare it to use it? How do I use it?

  • I imagine it is the properties of your object, that is, the Customer class. Anything, put the code of your Customer class

  • I’ll complement you so you can get a better sense, 1s.

  • Problems.. problems? I know so, but tell me above how bad it is rs

  • 1

    You have to make a class to access the database... and in it the connection...methods, etc... in another class, you create the client, or FDP in your case rsrs... the class needs to have the properties that the client should have... name, address, age, etc... it gets complicated to help you. I strongly recommend that you study a little more before developing. I know you’ve run out of time but trying to do it blind, you’ll just waste more time.

  • If I implement directly on the button the code I can solve?

  • Sure, what I said is fact, I’m doing something really useless that way I know I need to pass each field get;set such.. only that’s fucked.. thanks for the help!

  • 1

    Not necessarily on the button, but on the Form, then you can... just put textBoxNome.Text = reader["coluna_nome"].ToString(); it hurts to see such a thing, but, it sends see

  • 1

    It’s fucked up, college doesn’t teach you right. Then you have to go rogue.. I don’t even know if that considers it gambiarra.. but thanks anyway, your answer is the right one if I was doing right too :)

Show 6 more comments

Browser other questions tagged

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