title: Returning values from database to WebMethod
body: <p>I need to enter some value in the textbox end save it to the database.
  But if there is a duplicate value then the value must not be saved.</p>
  
  <p>Basically, string lvl is successfully passed to the WebMethod from front-end via ajax.</p>
  
  <p>Procedure getDuplicate is a simple select that checks if there is a value of lvl is already stored in the database. And InsertObject procedure inserts the value in the database.
  If the value(lvl) exists then the ID of that value is return and stored in the Count integer.</p>
  
  <p>The problem is if Count is returned with id number then if statement works,
  and if there is no value in the database Count just does not receive any values and the procedure fails and goes straight to the catch part of the code.</p>
  
  <p>I think there's a problem with the returning type from a database when there is no value in it. It is not INT or something.
  Can anyone help, please?</p>
  
  <pre><code>[WebMethod(EnableSession = true)]
              public static void GetCollection(string lvl)
              {
  
                string conn = ConfigurationManager.ConnectionStrings["Connection"].ConnectionString;
              using (SqlConnection connection = new SqlConnection(conn))
  
                  try
                  {
                      connection.Open();
                      SqlCommand cmdCount = new SqlCommand("getDuplicate", connection);
                      cmdCount.CommandType = CommandType.StoredProcedure;
                      cmdCount.Parameters.AddWithValue("@ObjekatName", lvl);
                      int count = (int)cmdCount.ExecuteScalar();
  
                      if (count &gt; 0)
                      {
  
                      }
                      else
                      {
                          SqlCommand cmdProc = new SqlCommand("InsertObjekat", connection);
                          cmdProc.CommandType = CommandType.StoredProcedure;
                          cmdProc.Parameters.AddWithValue("@ObjekatName", lvl);
                          cmdProc.ExecuteNonQuery();
                          //strMsg = "Saved successfully.";
                      }
  
                  }
                  catch
                  {
  
  
                  }
                  finally
                  {
                      connection.Close();
  
                  }
  
              return;
  </code></pre>
  
  <p>getDuplicate procedure</p>
  
  <pre><code>ALTER PROCEDURE [dbo].[GetDuplicate]  
  
      @ObjekatName nvarchar(20)
      AS
      BEGIN
  
      SET NOCOUNT ON  
      SELECT TOP 1000 [ObjekatID]
        ,[ObjekatName]
  
    FROM [MyApp].[dbo].[Objekat]
    WHERE  ObjekatName = @ObjekatName
      END
  </code></pre>