There is an exception message when I run the website
” Unable to cast object of type ‘System.DBNull’ to type
‘System.String’.”
emereging from the ‘value’ part of 'return (string)c.Parameters["@vat"].Value;‘ in the below code. I checked the stored procedure to see if it executes the query, it does and its output is a string as well. Can Anyone help..??
namespace CamOnlineAccess
{
public class Utilities
{
public SqlConnection GetConnection()
{
SqlConnection c = new SqlConnection();
c.ConnectionString = ConfigurationManager.ConnectionStrings["CamOnlineConnectionString"].ConnectionString;
return c;
}
public SqlCommand GetCommandSP(string SPName)
{
SqlCommand c = new SqlCommand();
c.Connection = GetConnection();
c.CommandType = CommandType.StoredProcedure;
c.CommandText = SPName;
c.CommandTimeout = 150;
return c;
}
}
}
public string ViewUserVat(string code)
{
CamOnlineAccess.Utilities u = new CamOnlineAccess.Utilities();
SqlCommand c = u.GetCommandSP("dbo.ViewUserVat");
c.Parameters.AddRange(new System.Data.SqlClient.SqlParameter[] {
new System.Data.SqlClient.SqlParameter("@code", System.Data.SqlDbType.VarChar,50),
new System.Data.SqlClient.SqlParameter("@vat",SqlDbType.VarChar, 50, System.Data.ParameterDirection.Output, false, ((byte)(0)), ((byte)(0)), "", System.Data.DataRowVersion.Current, null)});
c.Parameters["@code"].Value = code;
c.Connection.Open();
c.ExecuteScalar();//because we have output parameters
c.Connection.Close();
return (string)c.Parameters["@vat"].Value;
}
STRORED PROCEDURE
ALTER PROCEDURE [dbo].[ViewUserVat]
-- Add the parameters for the stored procedure here
@code varchar,
@vat varchar(50) output
AS
SELECT top 1 @vat=vattable from dbo.portfolio
where owner=@code
You return directly the parameter value assuming that your stored procedure will always find a record for the parameter
@codeand the columnvattableis never null.This is not the case as you can see, and you get a
DBNullin return.You should change your code to
Of course, assuming a
nullis an allowed/expected return value for the rest of your code.Otherwise, you can replace the
nullwith another acceptable value (eg string.Empty)