You could refactor your code like below and I think that you will get that you want. The problem is you don't specify anywhere to the CommandFunction
object the sql connection that will be used. I am not aware of this object, but I think that this is the problem. The solution below uses the class SqlCommand
.
using System.Configuration;
[WebMethod]
public static string GetCurrentToBin(string ToBin)
{
var connectionString = ConfigurationManager.ConnectionStrings["SqlConn"].ToString();
using(var conn = new SqlConnection(connectionString))
{
const string queryString = "exec sp_P_WMS_Stock_Adj_Validation_Proc @Bin";
var sqlCommand = new SqlCommand(queryString , conn);
sqlCommand.Parameters.AddWithValue("@Bin",ToBin);
conn.Open();
var reader = sqlCommand.ExecuteReader();
if(reader.Read() && !reader.IsDBNull(0))
{
return reader.GetString(0);
}
return null;
}
}
From the above code you could take two things:
- We don't explicitly close the sql connection. Instead of closing the connection explicitly, we let the using statement to do this for us. So anytime you want to create a new sql connection, wrap it in a using statement and you will not need again to remember to close the connection.
- Use only parameterized queries. Not doing so, you let your application open to sql injections.