jeudi 30 novembre 2017

if reader has rows then generate identification again

id made a code that will check the record in the table if has already had a record in the database if it has already an record then it will generate again. the problem it still show my identification that has already an record in database and showing it to my textbox.

here's my code:

    private void button1_Click(object sender, EventArgs e)
    {
       Random rand = new Random();
       int randomgenerator = rand.Next(001, 5);
       aidentification.Text = randomgenerator.ToString();        

        string exist = string.Empty;
        exist =  "Select * from fruit_stock " +
                  "where identification=@id";



        SqlConnection conn = new SqlConnection("server=WIN10;database=fruit_storage;user=fruit_admin;password=admin;");

       SqlCommand cmd = new SqlCommand()
    {
        Connection = conn,
        CommandType = CommandType.Text,
        CommandText = exist

    };
cmd.Parameters.AddWithValue("@id", aidentification.Text);
        try
        {
         conn.Open();
         SqlDataReader reader;
         reader = cmd.ExecuteReader();
            if (reader.HasRows){
               aidentification.Text = randomgenerator.ToString();
            }
         conn.Close();
        }
      catch (Exception ex) {
          MessageBox.Show(ex.Message);
      }

    }      
}

}




Aucun commentaire:

Enregistrer un commentaire