Reputation: 129
I have a code like below
txtbox1.Text = dtDetails.Rows[0]["columnName"] == null ? "--": dtDetails.Rows[0]["columnName"].ToString().Trim();
above line is always not null
even though dtDetails.Rows[0]["columnName"] is null
whereas
txtbox1.Text = dtDetails.Rows[0]["columnName"] == DBNull.Value ? "--": dtDetails.Rows[0]["columnName"].ToString().Trim();
works perfectly. why is that? and how a null
different over DBNull.Value
Upvotes: 2
Views: 6857
Reputation: 155185
ADO.NET (DataSet
, DataTable
, and DataRow
) represents SQL NULL
values with DBNull.Value
- this is to differentiate between runtime (C#/.NET) null
from SQL NULL
.
I strongly recommend reading this QA: What is the point of DBNull?
You can simplify your code, btw using DataRowExtensions
- (add a reference to System.Data.DataSetExtensions.dll
)
txtbox1.Text = dtDetails.Rows[0]["columnName"] == DBNull.Value ? "--": dtDetails.Rows[0]["columnName"].ToString().Trim();
Can be changed to:
txtbox1.Text = dtDetails.Rows[0].Field<String>("columnName")?.Trim() ?? "--";
The DataRowExtensions.Field<T>( this DataRow row, String name )
extension method checks for DBNull.Value
and returns null
- otherwise it returns the desired field without the overhead of looking-up the DataRow
value twice as your code currently does.
The OP says they're using Visual Studio 2010 (in 2019?!), so there are a few options:
If you have to use VS2010 (but why though?) you can hack your MSBuild project files to use a more modern C# compiler - but this is a complicated process - and there's no IDE editor support (so you'll get red-squiggly lines everywhere even though the project will build fine).
You could change the expression to perform Trim()
after the ?? "--"
clause:
txtbox1.Text = ( dtDetails.Rows[0].Field<String>("columnName") ?? "--" ).Trim();
You could use an extension method as a hacked-on conditional operator in a lambda:
static class Extensions
{
public static TOut N<TIn,TOut>( this TIn value, Func<TIn,TOut> whenNotNull )
where TIn : class
where TOut : class
{
if( value == null ) return null;
return whenNotNull( value );
}
}
Used like so:
txtbox1.Text = dtDetails.Rows[0].Field<String>("columnName").N( v => v.Trim() ) ?? "--";
Or extended further:
static class Extensions
{
public static TOut N<TIn,TOut>( this TIn value, Func<TOut> whenNull, Func<TIn,TOut> whenNotNull )
where TIn : class
where TOut : class
{
if( value == null ) return whenNull();
return whenNotNull( value );
}
}
Used like so:
txtbox1.Text = dtDetails.Rows[0].Field<String>("columnName").N( () => "--", v => v.Trim() );
Upvotes: 6
Reputation: 610
You have to check for the SQL NULL
not the Net Framework null
. They are two different Things
Upvotes: 0