Generate autoincrement in c #

1

I have a form in ASP.NET where I want to increase the Id in a textbox and show it in the text box, every time the user clicks on a button, it has to be updated.

Do this code but it does not work for me, it does not show the Folio in the text box

  private void Id()
    {
   SqlConnection conn = new SqlConnection();
        conn = new SqlConnection(this.conexion);
        conn.Open();
        SqlCommand cmd = new SqlCommand();
        try
        {
            cmd.CommandText = "select max(Folio) from Datos;";
            int valor = int.Parse(cmd.ExecuteScalar().ToString()) + 1;
            txtfolio.Text = Convert.ToString(valor);
        }
        catch(System.Exception ex)
        {

        }
 }

The method I added it in the High button:

      protected void Alta_Click(object sender, EventArgs e)
    {
      Id();
  }
    
asked by KlonDTS 20.02.2017 в 19:13
source

2 answers

0

If you do not have any rows you will return null, your program fails on the line where you convert "null" to int, that conversion can not be done, I recommend you change your query for something like this:

select case when max(Folio) is null then 0 else max(Folio) end from Datos

Thus, from the query you will return 0 when you have no records and avoid the problem of null

Edit:

I did not realize you had not assigned the connection to SqlCommand, add this:

cmd.Connection = conn;

Just before calling ExecuteScalar.

    
answered by 20.02.2017 / 19:19
source
0

Try an isnull:

select isnull(max(Folio), 0) from Datos;

I think that can work for you

    
answered by 20.02.2017 в 19:22