Why I'm getting this error? - c#

I have in stored procedure in SQL Server that use function and return RESULT a decimal.
In C# I need to get it but I get an error :
"INVALLD CastEXCEPTION was unhandeld by user code" "an exception of
type 'system.invaildCastException' occured...'
My C# code:
decimal? val = null;
SqlConnection con = new SqlConnection(conStr);
con.Open();
using (con)
{
SqlCommand cmd = new SqlCommand("dbo.spSetOrderDetails", con);
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter tvpParam = cmd.Parameters.AddWithValue("#OrderDetailsItemsTVP", dt);
tvpParam.SqlDbType = SqlDbType.Structured;
// this part of code return the SUM
SqlParameter returnParam = cmd.Parameters.Add("#RESULT", SqlDbType.Decimal);
returnParam.Direction = ParameterDirection.ReturnValue;
cmd.ExecuteNonQuery();
val = (decimal)cmd.Parameters["#RESULT"].Value;--HERE I GET THE EXCEPTION
}
con.Close();
return (decimal)val;

You can't cast the parameter with ParameterDirection.ReturnValue to a datatype that is not an integer.
The RETURN statement in T-SQL can only return integer values.
However, if you are absolutely certain that your Stored Procedure ends always with something like RETURN xxx then you could
val = Convert.ToDecimal(cmd.Parameters["#RESULT"].Value);

var res = cmd.Parameters["#RESULT"];
if(res != null && res.Value != null && res.Value != DbNull.value){
val = Convert.ToDecimal(res.Value);
}
else
val = defaultvalue;
This code will check if it's null or equal to dbnull.value. It will only cast if it's not null or dbnull.value. In case of null (or dbnull.value) it will simply set the value to defaultvalue for decimal.

Related

Cast Null DateTime Value From Database?

I'm performing a simple SELECT statement and I'm trying to return the value from a DateTime column from a SQL Server 2012 table. The problem is that when I return a NULL DateTime value I don't know how to manage this with my code below.
dtTrainingEnd = (DateTime)reader["TrainingEnd"];
I've searched for the last few days on an answer and cannot find something that will help me. I've found similar posts but still I cannot figure out how they can help me. Can you please explain how I can check to see if the datetime value returned from the database is NULL?
SqlConnection connRead = new SqlConnection(connReadString);
SqlCommand comm = new SqlCommand();
SqlDataReader reader;
string sql;
DateTime dtTrainingEnd = DateTime.Now;
int iTrainingSwipeID = 123;
sql = "SELECT TrainingEnd FROM TrainingSwipe WHERE TrainingSwipeID = " + iTrainingSwipeID;
comm.CommandText = sql;
comm.CommandType = CommandType.Text;
comm.Connection = connRead;
connRead.Open();
reader = comm.ExecuteReader();
while (reader.Read())
{
dtTrainingEnd = (DateTime)reader["TrainingEnd"];
}
connRead.Close();
If it might be null, you could use a nullable type... in this case, a DateTime? type:
while (reader.Read())
{
dtTrainingEnd = ((DateTime?)reader["TrainingEnd"]) ?? some_default_date;
}
connRead.Close();
Or just test for null if you'd rather do that:
while (reader.Read())
{
var endDate = reader["TrainingEnd"];
dtTrainingEnd = (endDate == null) ? some_default_date : (DateTime)endDate;
}
connRead.Close();
In both cases above, I assumed you want dtTrainingEnd to contain something if the date is NULL in the database, so some_default_date is some default DateTime.
Or if you want to leave dtTrainingEnd alone if the value is NULL, then just don't set it in that case:
while (reader.Read())
{
if ((reader["TrainingEnd"]) != null)
dtTrainingEnd = (DateTime)reader["TrainingEnd"];
}
connRead.Close();
*** Depending on how you connect to your db, you may have to replace null with DBNull.Value
With SQL you can do SELECT Coalesce(TrainingEnd,0) and if it is null, you would have a 1900-01-01 date...

C# DBNull.Value Inserting 0

I am trying to insert data into a SQL table. The data types I am having issues with are nullable floats. When the NULL values are inserted they change to 0. How can I keep them NULL.
private void InsertStatisticsData(DataTable dt)
{
//check isin periodicity and As of Date
foreach(DataRow row in dt.Rows)
{
DataTable queryResultTable = SQL.Query($#"SELECT * FROM Statistics
WHERE [CodeID] = '{row["CodeID"]}'
AND [Periodicity] = '{row["Periodicity"]}'
AND [As of Date] = '{row["As of Date"]}'");
if(queryResultTable.Rows.Count == 0)
{
//Check for Null Values
for(int i = 0; i < row.ItemArray.Count(); i++)
{
if (Convert.ToString(row[i]) == "")
row[i] = (object)DBNull.Value;
}
//Insert Data Into DataBase
SQL.NonQuery($#"INSERT INTO Statistics
VALUES ('{row["CodeID"]}' ,
'{row["Volatility"]}',
'{row["Beta"]}',
'{row["Info Ratio"]}',
'{row["Tracking"]}',
'{row["Drawdown"]}',
'{row["Periodicity"]}',
'{row["As of Date"]}')");
}
}
}
Nonquery Function:
public static void NonQuery(string query, string databaseName = "Database", string serverAddress = "server-name", int commandTimeout = 30)
{
string connString = $"Server = {serverAddress}; Database = {databaseName}; Trusted_Connection = True";
using (SqlConnection sqlConn = new SqlConnection(connString))
using (SqlCommand cmd = new SqlCommand(query, sqlConn))
{
sqlConn.Open();
cmd.CommandTimeout = commandTimeout;
cmd.ExecuteNonQuery();
}
}
You need to make sure your database column structure contains NULL types where you actually need them.
Also make sure you don't have any default constraints set, which automatically values the columns to 0 when null is assigned.
if(Convert.ToString(null) == "")
will be evaluated as false.
so below code won't get executed
row[i] = (object)DBNull.Value;
on a side note, you should use SqlParameters instead of appending values in a string.
This may seem a little heavy handed and bloaty, but if you use parameters (and you really, truly should), I have an extention method I use in my project to take any command object and loop through the parameters to turn a .NET null into a DbNull:
private static void ProcessNullParameters(this DbCommand command)
{
foreach (DbParameter param in command.Parameters)
{
if (param.Value == null)
param.Value = DBNull.Value;
}
}
This way, if your native object returns a null value, you can call the extention method against the command object. I couldn't tell what your SQL object was in your example (a framework of some type?), but presumably, somewhere behind the scenes something like this would be going on:
SqlCommand cmd = new SqlCommand("insert into Statistics values (#Code, #Volatility)", conn);
cmd.Parameters.Add("#Code", SqlDbType.VarChar);
cmd.Parameters.Add("#Volatility", SqlDbType.Decimal);
foreach (DataRow dr in dt.Rows)
{
cmd.Parameters[0].Value = dr["Code"];
cmd.Parameters[1].Value = dr["Volatility"];
// And here you convert your nulls to DbNull
cmd.ProcessNullParameters();
cmd.ExecuteNonQuery();
}
The alternative would be to do this on every value declaration that is nullable.
cmd.Parameters[0].Value = dr["Code"] ?? DbNull.Value
cmd.Parameters[1].Value = dr["Volatility"] ?? DbNull.Value;

Stored Procedure providing inconsistent return values

I'm working on a web form that validates data that the user uploads in the form of an Excel file. The code iterates through each row in the spreadsheet and checks against various rules, one of which is that the reference must be a unique value. I have a stored procedure that takes the userID and referenceNum as parameters:
BEGIN
SET NOCOUNT ON;
DECLARE #Status AS BIT
IF EXISTS (SELECT [TransactionMstID]
FROM [dbo].[tbl_TransactionMst]
WHERE [TransactionRef] = #DocumentNumber
AND [SupplierID] = #SupplierID)
BEGIN
SET #Status = 0
END
ELSE
BEGIN
SET #Status = 1
END
SELECT #Status AS [Status]
END
When I try different scenarios in SQL Server Management Studio (SSMS), I get the desired outputs e.g. a "0" when the reference exists and a "1" when it doesn't.
The problem arises in my C# code, it executes the stored procedure, but in my testing I get the same result irrespective of whether the data exists or not.
Here's the core of the C#:
bool returnValue = true;
if (Docnumber != null)
{
SqlConnection con = new SqlConnection(GlobalSettings.connection);
con.Open();
SqlCommand Cmd = new SqlCommand("p_ValRefNumber", con);
Cmd.CommandType = System.Data.CommandType.StoredProcedure;
Cmd.Parameters.AddWithValue("#DocumentNumber", Docnumber);
Cmd.Parameters.AddWithValue("#SupplierID", SupplierID);
Cmd.ExecuteNonQuery();
SqlDataReader dr = Cmd.ExecuteReader();
while (dr.Read())
{
bool Status = convertor.ConvertToBool(dr["Status"]);
string test = dr["Status"].ToString();
int testint = convertor.ConvertToInt(dr["Status"].ToString());
if (Status == false)
{
//throw new System.Exception(CEObj.GetErrorDesc(101));
returnValue = false;
}
}
dr.Close();
con.Close();
}
return returnValue;
}
No matter what the value of docnumber is in testing, it always shows as True. I've added a breakpoint so that I can check each time and then test in SSMS and I get conflicting results.
Is my logic wrong? Does Visual Studio treat the values differently? How is the result not consistent when converting it to a string - at the very least? It always seems to read a value of "1" in VS but varies in SSMS
Edit: here's my converter method's code:
public static bool ConvertToBool(object value)
{
bool result = false;
if (value != null)
{
bool.TryParse(value.ToString(), out result);
}
return result;
}
bool.TryParse isn't doing what the convertor (sic) code thinks it does.
bool.TryParse returns true if the value parameter equals bool.TrueString, which is the literal string "True". It returns false for any other value, which means it returns false for both 0 and 1.
Also, T-SQL bit values are numbers. The converter code isn't really necessary - just convert the return value to an Int32 and do a comparison.
using (var con = new SqlConnection(GlobalSettings.connection))
{
con.Open();
using (var cmd = new SqlCommand() { Connection = con, CommandType = CommandType.StoredProcedure, CommandText = "p_ValRefNumber" })
{
/* Assuming both parameters are integers.
Change SqlDbType if necessary. */
cmd.Parameters.Add(new SqlParameter() { ParameterName = "#DocumentNumber", SqlDbType = SqlDbType.Int, Value = Docnumber });
cmd.Parameters.Add(new SqlParameter() { ParameterName = "#SupplierID", SqlDbType = SqlDbType.Int, Value = SupplierID });
using (var reader = cmd.ExecuteReader(CommandBehavior.CloseConnection))
{
return dr.Read() && (Convert.ToInt32(dr["Status"]) == 1)
}
}
}

Error on C# when trying to fetch multiple data from database

I have this code in C#:
private void sqlConnLabel()
{
NoIDPenghuni = new SqlParameter();
SqlConnection con = new SqlConnection(strCon);
com2 = new SqlCommand();
com2.Connection = con;
con.Open();
com2.CommandType = CommandType.StoredProcedure;
com2.CommandText = "label";
NoIDPenghuni.SqlDbType = SqlDbType.VarChar;
NoIDPenghuni.Size = 50;
NoIDPenghuni.ParameterName = "#NoIDPenghuni";
NoIDPenghuni.Value = NoIDPenghuniC;
NoIDPenghuni.Direction = ParameterDirection.Input;
com2.Parameters.Add(NoIDPenghuni);
string NamaPenghuni;
string JKPenghuni;
string NoTelpPenghuni;
string AlamatPenghuni;
string NoKamar;
NamaPenghuni = Convert.ToString(com2.ExecuteScalar());
JKPenghuni = Convert.ToString(com2.ExecuteScalar());
NoTelpPenghuni = Convert.ToString(com2.ExecuteScalar());
AlamatPenghuni = Convert.ToString(com2.ExecuteScalar());
NoKamar = Convert.ToString(com2.ExecuteScalar());
SqlDataReader reader = com2.ExecuteReader();
while (reader.Read())
{
NamaPenghuni = reader["NamaPenghuni"] == DBNull.Value ? null : (string)reader["NamaPenghuni"];
JKPenghuni = reader["JKPenghuni"] == DBNull.Value ? null : (string)reader["JKPenghuni"];
NoTelpPenghuni = reader["NoTelpPenghuni"] == DBNull.Value ? null : (string)reader["NoTelpPenghuni"];
AlamatPenghuni = reader["AlamatPenghuni"] == DBNull.Value ? null : (string)reader["AlamatPenghuni"];
NoKamar = reader["NoKamar"] == DBNull.Value ? null : (string)reader["NoKamar"];
}
label9.Text = NoIDPenghuniC;
label8.Text = NamaPenghuni;
if (JKPenghuni == "P")
label7.Text = "Male";
else
label7.Text = "Female";
label6.Text = NoTelpPenghuni;
label18.Text = AlamatPenghuni;
label5.Text = NoKamar;
con.Close();
}
When I try to run it keeps telling me
IndexOutOfRangeException was unhandled.
I think the data won't be fetched into my C#. It only takes the 'NamaPenghuni'
For example: if I take the data with NoIDPenghuni='110801101, the NamaPenghuni should be Priska Hapsari, the JKPenghuni should be W, the NoTelpPenghuni should be 08567711332, and the AlamatPenghuni should be Jl. Mega Cinere No. 29, Cinere.
But on my locals section I can see that all those string variables values are Priska Hapsari.
What did I do wrong?
You call for 5 times the ExecuteScalar before the ExecuteReader.
ExecuteScalar returns the first column of the first row (just one result).
Calling it 5 times results in the same value for the all 5 variables
The IndexOutOfRange exception could be caused by the following ExecuteReader that expects to find 5 columns in the returned values, but we can't see if the StoredProcedure returns effectively 5 values per row

Handling ExecuteScalar() when no results are returned

I am using the following SQL query and the ExecuteScalar() method to fetch data from an Oracle database:
sql = "select username from usermst where userid=2"
string getusername = command.ExecuteScalar();
It is showing me this error message:
System.NullReferenceException: Object reference not set to an instance of an object
This error occurs when there is no row in the database table for userid=2.
How should I handle this situation?
According to MSDN documentation for DbCommand.ExecuteScalar:
If the first column of the first row in the result set is not found, a
null reference (Nothing in Visual Basic) is returned. If the value in
the database is null, the query returns DBNull.Value.
Consider the following snippet:
using (var conn = new OracleConnection(...)) {
conn.Open();
var command = conn.CreateCommand();
command.CommandText = "select username from usermst where userid=2";
string getusername = (string)command.ExecuteScalar();
}
At run-time (tested under ODP.NET but should be the same under any ADO.NET provider), it behaves like this:
If the row does not exist, the result of command.ExecuteScalar() is null, which is then casted to a null string and assigned to getusername.
If the row exists, but has NULL in username (is this even possible in your DB?), the result of command.ExecuteScalar() is DBNull.Value, resulting in an InvalidCastException.
In any case, the NullReferenceException should not be possible, so your problem probably lies elsewhere.
First you should ensure that your command object is not null. Then you should set the CommandText property of the command to your sql query. Finally you should store the return value in an object variable and check if it is null before using it:
command = new OracleCommand(connection)
command.CommandText = sql
object userNameObj = command.ExecuteScalar()
if (userNameObj != null)
string getUserName = userNameObj.ToString()
...
I'm not sure about the VB syntax but you get the idea.
I just used this:
int? ReadTerminalID()
{
int? terminalID = null;
using (FbConnection conn = connManager.CreateFbConnection())
{
conn.Open();
FbCommand fbCommand = conn.CreateCommand();
fbCommand.CommandText = "SPSYNCGETIDTERMINAL";
fbCommand.CommandType = CommandType.StoredProcedure;
object result = fbCommand.ExecuteScalar(); // ExecuteScalar fails on null
if (result.GetType() != typeof(DBNull))
{
terminalID = (int?)result;
}
}
return terminalID;
}
The following line:
string getusername = command.ExecuteScalar();
... will try to implicitly convert the result to string, like below:
string getusername = (string)command.ExecuteScalar();
The regular casting operator will fail if the object is null.
Try using the as-operator, like this:
string getusername = command.ExecuteScalar() as string;
sql = "select username from usermst where userid=2"
var _getusername = command.ExecuteScalar();
if(_getusername != DBNull.Value)
{
getusername = _getusername.ToString();
}
Check out the example below:
using System;
using System.Data;
using System.Data.SqlClient;
class ExecuteScalar
{
public static void Main()
{
SqlConnection mySqlConnection =new SqlConnection("server=(local)\\SQLEXPRESS;database=MyDatabase;Integrated Security=SSPI;");
SqlCommand mySqlCommand = mySqlConnection.CreateCommand();
mySqlCommand.CommandText ="SELECT COUNT(*) FROM Employee";
mySqlConnection.Open();
int returnValue = (int) mySqlCommand.ExecuteScalar();
Console.WriteLine("mySqlCommand.ExecuteScalar() = " + returnValue);
mySqlConnection.Close();
}
}
from this here
SQL NULL value
equivalent in C# is DBNull.Value
if a NULLABLE column has no value, this is what is returned
comparison in SQL: IF ( value IS NULL )
comparison in C#: if (obj == DBNull.Value)
visually represented in C# Quick-Watch as {}
Best practice when reading from a data reader:
var reader = cmd.ExecuteReader();
...
var result = (reader[i] == DBNull.Value ? "" : reader[i].ToString());
In my experience, there are some cases the returned value can be missing and thus execution fails by returning null. An example would be
select MAX(ID) from <table name> where <impossible condition>
The above script cannot find anything to find a MAX in. So it fails. In these such cases we must compare the old fashion way (compare with C# null)
var obj = cmd.ExecuteScalar();
var result = (obj == null ? -1 : Convert.ToInt32(obj));
If you either want the string or an empty string in case something is null, without anything can break:
using (var cmd = new OdbcCommand(cmdText, connection))
{
var result = string.Empty;
var scalar = cmd.ExecuteScalar();
if (scalar != DBNull.Value) // Case where the DB value is null
{
result = Convert.ToString(scalar); // Case where the query doesn't return any rows.
// Note: Convert.ToString() returns an empty string if the object is null.
// It doesn't break, like scalar.ToString() would have.
}
return result;
}
Always have a check before reading row.
if (SqlCommand.ExecuteScalar() == null)
{
}
This is the easiest way to do this...
sql = "select username from usermst where userid=2"
object getusername = command.ExecuteScalar();
if (getusername!=null)
{
//do whatever with the value here
//use getusername.toString() to get the value from the query
}
In your case either the record doesn't exist with the userid=2 or it may contain a null value in first column, because if no value is found for the query result used in SQL command, ExecuteScalar() returns null.
Alternatively, you can use DataTable to check if there's any row:
SqlCommand cmd = new SqlCommand("select username from usermst where userid=2", conn);
SqlDataAdapter adp = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
adp.Fill(dt);
string getusername = "";
// assuming userid is unique
if (dt.Rows.Count > 0)
getusername = dt.Rows[0]["username"].ToString();
private static string GetUserNameById(string sId, string connStr)
{
System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection(connStr);
System.Data.SqlClient.SqlCommand command;
try
{
// To be Assigned with Return value from DB
object getusername;
command = new System.Data.SqlClient.SqlCommand();
command.CommandText = "Select userName from [User] where userid = #userid";
command.Parameters.AddWithValue("#userid", sId);
command.CommandType = CommandType.Text;
conn.Open();
command.Connection = conn;
//Execute
getusername = command.ExecuteScalar();
//check for null due to non existent value in db and return default empty string
string UserName = getusername == null ? string.Empty : getusername.ToString();
return UserName;
}
catch (Exception ex)
{
throw new Exception("Could not get username", ex);
}
finally
{
conn.Close();
}
}
Slight conjecture: if you check the stack for the exception, it is being thrown then the ADO.NET provider for Oracle is reading the underlying rowset to get the first value.
If there is no row, then there is no value to find.
To handle this case execute for a reader and handle Next() returning false for the case of no match.
I Use it Like This with Microsoft Application Block DLL (Its a help library for DAL operations)
public string getCopay(string PatientID)
{
string sqlStr = "select ISNULL(Copay,'') Copay from Test where patient_id=" + PatientID ;
string strCopay = (string)SqlHelper.ExecuteScalar(CommonCS.ConnectionString, CommandType.Text, sqlStr);
if (String.IsNullOrEmpty(strCopay))
return "";
else
return strCopay ;
}
I have seen in VS2010
string getusername = command.ExecuteScalar();
gives compilation error,
Cannot implicitly convert type object to string.
So you need to write
string getusername = command.ExecuteScalar().ToString();
when there is no record found in database it gives error
Object reference not set to an instance of an object
and when I comment '.ToString()', it is not give any error. So I can say ExecuteScalar not throw an exception. I think anserwer given by #Rune Grimstad is right.
I had this issue when the user connecting to the database had CONNECT permissions, but no permissions to read from the database. In my case, I could not even do something like this:
object userNameObj = command.ExecuteScalar()
Putting this in a try/catch (which you should probably be doing anyway) was the only way I could see to handle the insufficient permission issue.
object objUserName;
objUserName = command.ExecuteScalar();
if (objUserName == null) //if record not found ExecuteScalar returns null
{
return "";
}
else
{
if (objUserName == DBNull.Value) //if record found but value in record field is null
{
return "";
}
else
{
string getusername = objUserName.ToString();
return getusername;
}
}
/* Select some int which does not exist */
int x = ((int)(SQL_Cmd.ExecuteScalar() ?? 0));
I used this in my vb code for the return value of a function:
If obj <> Nothing Then
Return obj.ToString()
Else
Return ""
End If
Try this code, it appears to solve your problem.
Dim MaxID As Integer = Convert.ToInt32(IIf(IsDBNull(cmd.ExecuteScalar()), 1, cmd.ExecuteScalar()))
I'm using Oracle.
If your sql returns numeric value, which is int, you need to use Convert.ToInt32(object). Here is the example below:
public int GetUsersCount(int userId)
{
using (var conn = new OracleConnection(...)){
conn.Open();
using(var command = conn.CreateCommand()){
command.CommandText = "select count(*) from users where userid = :userId";
command.AddParameter(":userId", userId);
var rowCount = command.ExecuteScalar();
return rowCount == null ? 0 : Convert.ToInt32(rowCount);
}
}
}
Try this
sql = "select username from usermst where userid=2"
string getusername = Convert.ToString(command.ExecuteScalar());

Categories

Resources