How to return the last Record of an SQL column in a textbox?

Asked

Viewed 328 times

0

I am developing an application for my technical course that will register customers, in case I would like that before registering the client the field code returned the last code of the table sql + 1 to show automatically the code that will be registered in the client being registered. if anyone can help me would be very grateful. I tried this code in the form to return the value:

private void cad_cliente_Load(object sender, EventArgs e)
        {
            comando.Connection = conn;
            {
                conn.Open();
                const int i = 1;
                comando.CommandText = "SELECT MAX(cod_cli) FROM cad_cli";
                dr = comando.ExecuteReader();

                if (dr.HasRows)
                {
                    while (dr.Read())
                    {
                        textBoxCod.Text = "SELECT MAX(cod_cli) FROM cad_cli" + i;
                    }
                }

            }

        }

inserir a descrição da imagem aqui

1 answer

1

When you only need one value you can and should use the Executescalar

The code would look something like this:

string sql = "SELECT MAX(cod_cli) FROM cad_cli";
using (var conn = new SqlConnection(sua_connection_string))
{                           
    var comando = new SqlCommand(sql, conn);       
    try
    {
        conn.Open();
        int maxId = (int)comando.ExecuteScalar();
        textBoxCod.Text = (maxId + 1).ToString();
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }                       
}
  • in the field "using (var Conn = new Sqlconnection(sua_connection_string))" in this "sua_connection_string" I used Conn at the beginning of the code, thus : Sqlconnection Conn = new Sqlconnection("Data Source=luanpc SQLEXPRESS; Initial Catalog=client; Integrated Security=True"); it would be "Conn" same ?

Browser other questions tagged

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