select the maximum value, and automatically generate the Product Code.

ELIRDFUL 185 Reputation points
2023-12-28T12:57:17.5733333+00:00

Hello everyone

 

I am trying to select the maximum value, and automatically generate the Product Code.

 

This is the Code, but it doesn't come out.

try
{
    using(var Conexion = new SqlConnection(VariablesGlobales.CadenaConexion))
    {
        Conexion.Open();
        string consultaSQL = "select Max(CodigoProducto) As maximo FROM TblaProducto2";
        var comando = new SqlCommand(consultaSQL, Conexion);
        SqlDataReader LD = comando.ExecuteReader();
        if(LD.Read() == true)
            if(maximo = 0)
            {
                txtCodigo1.Text = "1";
            }
            else
            {
                maximo = maximo + 1;
                txtCodigo1.Text = maximo;
            }
            {}
    }
}
catch(Exception ex) //
{
    MessageBox.Show("Error al intentar seleccionar el valor maximo");
    MessageBox.Show(ex.Message); // Muestra el Mensaje de Error.            
}

User's image

I count on your help

Developer technologies C#
{count} votes

Accepted answer
  1. P a u l 10,761 Reputation points
    2023-12-28T13:09:22.8766667+00:00

    Is this what you're after?:

    LD.Read();
    
    var max = reader.GetInt32(3);
    
    txtCodingo1.Text = max + 1;
    

    Disclaimer: it's normally better to let SQL decide new IDs with an auto-incrementing ID column:

    https://www.w3schools.com/sql/sql_autoincrement.asp

    This avoids inevitable race conditions, particularly if this is a multi-user app.

    1 person found this answer helpful.

2 additional answers

Sort by: Most helpful
  1. Bruce (SqlWork.com) 77,686 Reputation points Volunteer Moderator
    2023-12-28T18:00:06.72+00:00

    Also be sure not to use this code in a multiple user environment, as you could get duplicate product codes.

    If used in a multiple user environment, be sure the first save of the product code is to unique column, and catch the duplicate key error. This will tell your code it needs to generate a new key.

    1 person found this answer helpful.

  2. ELIRDFUL 185 Reputation points
    2023-12-29T14:58:54.7466667+00:00

    solved 100x%

    I was able to autonumber it in the database.

    thank you...

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.