I am trying to compare the value of a row esmcost with psmcost of table wsmtbl but esmcost cost value is null due to which I am getting the following error:
Operator '<>' is not defined for type 'DBNull' and type 'DBNull'
Is there any way to change the null value to zero?
This is the C# code
ds.Tables["wsmtbl"].Rows[0]["esmcost"] <> ds.Tables["wsmtbl"].Rows[0]["psmcost"]
Try the following.
Decimal esmcost;
if (ds.Tables["wsmtbl"].Rows[0]["esmcost"] == DBNull.Value)
esmcost = 0.00;
else
esmcost = Convert.ToDecimal(ds.Tables["wsmtbl"].Rows[0]["esmcost"]);
Decimal psmcost;
if (ds.Tables["wsmtbl"].Rows[0]["psmcost"] == DBNull.Value)
psmcost = 0.00;
else
psmcost = Convert.ToDecimal(ds.Tables["wsmtbl"].Rows[0]["psmcost"]);
if (esmcost != psmcost)
{
...
}
One could use the ternary operator syntax but I chose the above for readability reasons. For example:
Decimal esmcost = ds.Tables["wsmtbl"].Rows[0]["esmcost"]
== DBNull.Value ? 0.00 : Convert.ToDecimal(ds.Tables["wsmtbl"].Rows[0]["esmcost"]);
Try this,
if(ds.Tables["wsmtbl"].Rows[0]["esmcost"] == DBNull.Value)
{
ds.Tables["wsmtbl"].Rows[0]["esmcost"] = 0;
}
ds.Tables["wsmtbl"].Rows[0]["esmcost"] != ds.Tables["wsmtbl"].Rows[0]["psmcost"];
I'am new using C# and i have problem when using if inside "public object" method, this my code :
public object Login([FromBody] MailParameters data)
{
UmbracoDatabase db = ApplicationContext.DatabaseContext.Database;
var select = new Sql("SELECT UserID FROM Users where Email='" + data.Email + "';");
var ids = db.Fetch<listUsersChecks>(select);
if (ids)
{
var getByEncrypt = new Sql("SELECT * FROM Users where Email='" + data.Email + "' AND password='" + data.Password + "';");
var listue = db.Fetch<listUsers>(getByEncrypt);
}else{
var listue = "";
}
return listue;
}
the output is :
error CS0029: Cannot implicitly convert type 'System.Collections.Generic.List<LoginController.listUsersChecks>' to 'bool'
the error is in if(ids){ , how to solved this?
thanks
Look at the error message, if statement required a Boolean, but you feed in with a List. In this case, your ids is a list List<LoginController.listUsersChecks>
Since it's a list, you can check by counting number of item in this list:
if(ids.Count >0){} else{}
var ids = db.Fetch<listUsersChecks>(select);
This will give you a List<listUsersChecks> and an if condition needs a bool to evaluate if it should be executed or not.
If you want to execute the if statement when you have entries in your list you should use
if(ids.Count > 0)
{
//logic
}
Count is a property of List and gives the number of items in the list.
To make it even more clearer you could write this as well.
bool hasItems = ids.Count > 0;
if(hasItems)
{
//logic
}
You could use the Any method of LINQ as well.
Determines whether any element of a sequence exists or satisfies a
condition.
That would look like
if(ids.Any())
{
//logic
}
For more information have a look at 101 LINQ-Samples
not all your code paths return a value. you have to define your return object prior to the if statement and inside each branch just set it.and as for ids, it's not a valid boolean expression by itself, you may try ids.Any()
It looks like you are expecting C# to support "truthy" and "falsey" values like Javascript. In C#, there is no concept of "truthy" or "falsey". The expression in the if must evaluate to a boolean true or false. What you really want to do is use something like this Linq expression:
if(ids.Any())
{
...
}
Hi I am checking datatable row value. If the value is not null or empty then checking for the value if it is a number. Otherwise add in to the error list. If the value is null or empty then assign null.
The code is working fine but I want to check if there is any better way to do this. Any suggestions would be appreciated.
here is my code.
if (!(row.IsNull("limit") || row["limit"].ToString().Length == 0))
{
//Check if value is number
if (int.TryParse(row["limit"].ToString().Trim(), out n))
{
query.limit = Convert.ToInt32(row["limit"].ToString().Trim());
}
else
{
errorList.Add("limit: Value:" + row["limit"].ToString());
}
}
//if value is null then assign null
else
{
query.limit = null;
}
Few points I have to mention here:
By using int.TryParse to parse the row["limit"] you will get the converted value in the out parameter, then you need not convert the same again to an integer using Convert.ToInt32, use the out parameter instead.
The first if can be simplified using NullConditional operators(?.).
There may be chances for getting row as null, in such cases, you need to check for null before accessing row["limit"] otherwise NullReference will be the result
I think it will be more clear and simple if you do like this:
if (row != null && row["limit"]?.ToString() != "") // means row["limit"] definitely has some value
{
int currentLimit = 0;
if (int.TryParse(row["limit"].ToString().Trim(), out currentLimit))
{
query.limit = currentLimit ;
}
else
{
errorList.Add("limit: Value:" + row["limit"].ToString());
}
}
else
{
query.limit = null;
}
If you are not using c# 6 then row["limit"]?.ToString() will not work in this case you have to use the condition as like this:
if (row != null && row["limit"] != null && row["limit"].ToString() != "")
I am using typed data set in my application and I have a data table with two columns which are of System.Int32.AllowDBNULL = true and NULLVALUE = throw exception and default value = 1. I am using this property of datatable in my code like this:
if (rr.ForenameStatus != -1 && rr.ForenameStatus == 0)
{
}
but I am getting this error:
The value for column 'ForenameStatus' in table 'Registrant' is DBNull.
I tried to change NULLVALUE of column to NULL or empty in dataset properties but I get error:
property value is not valid
I tried using this:
if (rr.ForenameStatus != System.DBNull.Value && rr.ForenameStatus == 0)
{
}
but It says Operator != can not be applied to operands of int and dbnull
Please suggest me solution to this.
Set AllowDBNULL = true and call IsForenameStatusNull method to check on NULL value.
Try this:
if (rr.ForenameStatus.ToString()!="" && rr.ForenameStatus == 0)
{
}
This is as an alternative. You may try converting the int value to string and compare against empty string to identify the nulls.
I have a datareader that return a lsit of records from a sql server database. I have a field in the database called "Additional". This field is 50% of the time empty or null.
I am trying to write code that checks if this field isnull. The logic behind this is:
If the field "Additional" contains text then display the info otherwise hide the field.
I have tried:
if (myReader["Additional"] != null)
{
ltlAdditional.Text = "contains data";
}
else
{
ltlAdditional.Text = "is null";
}
The above code gives me this error:
Exception Details: System.IndexOutOfRangeException: Additional
Any help would be greatly appreciated...
See Also:
Check for column name in a SqlDataReader object
if (myReader["Additional"] != DBNull.Value)
{
ltlAdditional.Text = "contains data";
}
else
{
ltlAdditional.Text = "is null";
}
if (myReader.HasRows) //The key Word is **.HasRows**
{
ltlAdditional.Text = "Contains data";
}
else
{
ltlAdditional.Text = "Is null Or Empty";
}
I haven't used DataReaders for 3+ years, so I wanted to confirm my memory and found this. Anyway, for anyone who happens upon this post like I did and wants a method to test IsDBNull using the column name instead of ordinal number, and you are using VS 2008+ (& .NET 3.5 I think), you can write an extension method so that you can pass the column name in:
public static class DataReaderExtensions
{
public static bool IsDBNull( this IDataReader dataReader, string columnName )
{
return dataReader[columnName] == DBNull.Value;
}
}
Kevin
This is the correct and tested solution
if (myReader.Read())
{
ltlAdditional.Text = "Contains data";
}
else
{
ltlAdditional.Text = "Is null";
}
I also use OleDbDataReader.IsDBNull()
if ( myReader.IsDBNull(colNum) ) { retrievedValue = ""; }
else { retrievedValue = myReader.GetString(colNum); }
First of all, you probably want to check for a DBNull not a regular Null.
Or you could look at the IsDBNull method
In addition to the suggestions given, you can do this directly from your query like this -
SELECT ISNULL([Additional], -1) AS [Additional]
This way you can write the condition to check whether the field value is < 0 or >= 0.
#Joe Philllips
SQlDataReader.IsDBNull(int index) requires the ordinal number of the column. Is there a way to check for nulls using Column Name, and not it's Ordinal Number?
Try this simpler equivalent syntax:
ltlAdditional.Text = (myReader["Additional"] == DBNull.Value) ? "is null" : "contains data";
I also experiencing this kind of problem but mine, i'm using DbDataReader as my generic reader (for SQL, Oracle, OleDb, etc.). If using DataTable, DataTable has this method:
DataTable dt = new DataTable();
dt.Rows[0].Table.Columns.Contains("SampleColumn");
using this I can determine if that column is existing in the result set that my query has. I'm also looking if DbDataReader has this capability.
This
Example:
objCar.StrDescription = (objSqlDataReader["fieldDescription"].GetType() != typeof(DBNull)) ? (String)objSqlDataReader["fieldDescription"] : "";
Best thing to get this done in query. However, if query bond to other functions than checking DBNull.Value in while loop would address the issue.
if (reader.HasRows)
{
while (reader.Read())
{
(reader["Additional"] != DBNull.Value) ? "contains data" : "is null";
}
}
AMG - Sorry all, was having a blond moment. The field "Additional" was added to the database after I had initially designed the database.
I updated all my code to use this new field, however I forgot to update the actual datareader code that was making the call to select the database fields, therefore it wasn't calling "Additional"