String.IsNullOrEmpty check with Data Table cell - c#

If I have a Data Table and I want to see if the value contained within a specific cell is empty I would use this.
foreach(DataRow row in DataTable.Rows)
{
bool isEmpty = String.IsNullOrEmpty(row["MyColumn"].ToString());
}
but what happens if the value in row["MyColumn"] is null. Wouldn't the .ToString() throw an exception? Yet when I try the following ..
bool isEmpty = String.IsNullOrEmpty(row["MyColumn"]);
I get an invalid argument exception because the IsNullOrEmpty() method is looking for a string object.
So what is the proper way to check if a specific cell in a Data Table is empty or null?

Change your statement to this,
bool isEmpty = String.IsNullOrEmpty(row["MyColumn"]?.ToString());
?. means run the process .ToString() only if row["MyColumn"] is not null.

Basically just adding this for the sake of completeness... but if for some reason you aren't using C# 6 or above, you can always do it the "old fashioned way":
bool isEmpty = row["MyColumn"] == null || string.IsNullOrEmpty(row["MyColumn"].ToString());

You could instead use the Field<T>() method of the DataRow:
bool isEmpty = String.IsNullOrEmpty(row.Field<string>("MyColumn"));
This provides strongly typed access to the row values.
You can use it with other types too, so no need to parse int or DataTime, for example.
var myDate = row.Field<DateTime>("MyDate"); // DateTime
var myInt = row.Field<int>("MyInt"); // int
It also works with nullable types:
var myDate = row.Field<DateTime?>("MyDate"); // DateTime? (Nullable)
if (myDate.HasValue)
{
...
}

Related

SqlDataReader Convert Int to Int?

I need to return a NULL or Blank value for Apvl_Lvl_Id if the SQL result returns NULL as the integration this passes the Apvl_Lvl_Id value to can't handle a value if it doesn't match an existing value for that instance.
I can't figure out what I'm missing, hoping someone can offer some pointers. Hope the below code is enough for an example.
while (dr.Read())
{
if(dr.IsDBNull(Apvl_Lvl_Id))
{
int? Apvl_Lvl_IdNULL;
Apvl_Lvl_Id = Apvl_Lvl_IdNULL;
}
else
{
Apvl_Lvl_Id = dr.GetInt32(0);
}
}
Sorry, but that code makes little sense. Apparently, Apvl_Lvl_Id is supposed to be the column ordinal - effectively the zero-based count of the column in a row - that you check for being DBNull. Then you are trying to assign the actual column's value to that ordinal? Apart from that, there is just no way you can assign null to an int. Introduce a separate variable, say, Apvl_Lvl_Value, make it an Nullable<int> (or int?) and assign the the column's value as required (actual value or null).
In "short", the code should more like this:
while (dr.Read())
{
int? Apvl_Lvl_Value;
// Check if the value of the column with the ordinal Apvl_Lvl_Id is DBNull
if(dr.IsDBNull(Apvl_Lvl_Id))
{
// If so, use .NET "null" for the rest of the logic.
Apvl_Lvl_Value = null;
}
else
{
// Use the actual columns (non-NULL) value.
Apvl_Lvl_Value = dr.GetInt32(Apvl_Lvl_Id);
}
// Do something with the column's value, stored in Apvl_Lvl_Value
}
Now, some things here are guesswork which are not really clear otherwise from your question, but generally, the above is a "pattern" by which one would use IsDBNull() and
a Get*() method together.
And why don't you just set
Apvl_lvl_Id = null;

Cannot implicitly convert type 'string' to 'int' errors

I want to save the information entered in ASP.NET to the database and display it in GridView but the information that needs to be entered is dropdownlist selected.
The IDs of the elections held are kept.
int birim =Convert.ToInt32(DDLbirim.SelectedValue);
and
int birim=(int)DDLbirim.SelectedValue;
I write but in the form of an error. How can I help you track a way?
There are several ways to convert a string to int.
Convert.ToInt32 is one of them, but like int.Parse, it raises an exception if your string is not a numeric
To avoid the exception, you can use TryParse
The TryParse method is like the Parse or Convert.ToInt32 method, except the TryParse method does not throw an exception if the conversion fails.
bool isSuccees= Int32.TryParse(DDLbirim.SelectedValue, out birim );
I think your DDLbirim.SelectedValue is not a valid int so it can not cast it to a int hence the exception.
I would do an int.TryParse to check if the value is a valid int.
bool successfullyParsed = int.TryParse(DDLbirim.SelectedValue, out birim);
if (successfullyParsed){
// ...
}
The selectedValue is null when the dropdown isn't selected as valid. Else, as long as each item in the dropdown have a valid value, it will return as proper
The value is of type object, as it can store any type available.
Make sure that the values being set in the designer or backend are indeed integer and not string. Good way to identify would be as
if (ddlBrim.SelectedIndex >=0) {
var value = ddlBrim.SelectedValue;
// Inspect value in debugger to validate at this point
int intValue = -1;
if (Int32.TryParse(ddlBrim.SelectedValue, out intValue) {
// use the result value here
}
}
If DDLbirim.SelectedValue is null or if contains non-integer value you have to use TyrParse. TryParse handles nulls and invalid strings
int birim=0;
if (int.TryParse(DDLbirim.SelectedValue, out birim)){
}
Please make sure that you correctly bind the dropdownlist i.e. with displayMember, ValueMember (field must be parsable to the integer value), and Datasource.
Once it's fine, you can try to parse it.

Handling Null values in GetSQLDateTime and GetSQLMoney

AS part of an import I'm writing I'm using parameterised values, however the database i'm exporting to cannot handle NULL values, so I need to find a way to handle NULL values.
The closest I've gotten is:
if (tenantexportReader.GetSqlMoney(8).ToDecimal().Equals(null))
{
tenantimportCommand.Parameters["PRICEFINAL"].Value = "0.00";
}
else
{
tenantimportCommand.Parameters["PRICEFINAL"].Value = tenantexportReader.GetSqlMoney(8).ToDecimal();
}
and A similar thing with SQLDateTime
if (tenantexportReader.GetDateTime(9).ToShortDateString().Equals(null))
{
tenantimportCommand.Parameters["TENSDATE"].Value = "0.00";
}
else
{
tenantimportCommand.Parameters["TENSDATE"].Value = tenantexportReader.GetDateTime(9).ToShortDateString();
}
However this does not appear to work, instead I receive the following:
Message=Data is Null. This method or property cannot be called on Null values.
Instead of
if (tenantexportReader.GetSqlMoney(8).ToDecimal().Equals(null))
you should probably use
if (tenantexportReader.IsDbNull(8))
Since the value in the database is NULL (which is DbNull.Value in c#), I assume that GetSqlMoney and GetSqlDateTime throw the exception you received. DbNull.Value cannot be converted to SqlMoney or DateTime.
Check if the value is null via IsDbNull before calling GetSqlMoney or GetSqlDateTime.
So your final if statements should look something like this:
if (tenantexportReader.IsDbNull(8))
{
tenantimportCommand.Parameters["PRICEASK"].Value = "0.00";
}
else
{
tenantimportCommand.Parameters["PRICEFINAL"].Value = tenantexportReader.GetSqlMoney(8).ToDecimal();
}
Why would you assign a string to a monetary value???
Probably what you would want to do is like this:
var priceFinal = tenantexportReader.GetSqlMoney(8);
tenantimportCommand.Parameters["PRICEFINAL"].Value = (decimal)(priceFinal.IsNull ? 0 : priceFinal);
I really don't understand why you set it to "0.00" (string) when it is null and to a decimal value when it is not null.
And also for date/datetime values, again, why do you ever use string conversions and invite errors? Simply pass a date as a datetime.

Nullable Object must have a value #2

I'm trying to reuse the same code I've always used but now it is encountering an error.
I'm looping through various user tables, and in there I do this:
DateTime dcdt = (DateTime)u.DateCreated;
DateTime lldt = (DateTime)u.LastLogon;
userRow["DateCreated"] = dcdt.ToShortDateString();
inside the loop. I get the error:
System.InvalidOperationException: Nullable object must have a value.
The error highlights "lldt" line, instead of "dcdt" which comes first. That is strange in and of itself. Both these fields in the database "allow nulls" is checked. And they both could be null or neither might be null.
The two values are both listed as DateTime? types through intellisense.
I don't understand why ASP.NET refuses to allow me to output blank for null dates. If it is empty/null, then logic would suggest that ASP.NET should just print nothing.
How else am I suppose to output null dates? I tried adding if statements to prevent trying to cast null DateTimes, but it doesn't help, it makes no sense.
As you've said, the data type of u.LastLogon is DateTime?. This means that it may or may not have a value. By casting to DateTime, you are requiring it to have a value. In this case, it does not.
Depending on what you're trying to do with it, you may want to check the HasValue property:
userRow["LastLogon"] = u.LastLogin.HasValue ?
(object) u.LastLogin.ToShortDateString() : DBNull.Value;
If your database LastLogon column is of DateTime type, then you should be able to do:
userRow["LastLogon"] = u.LastLogin.HasValue ?
(object) u.LastLogin.Value : DBNull.Value;
You need to do something like the following in your data access code:
DataTable dt = ExecuteSomeQuery() ;
object value = dt.Rows[0]["nullable_datetime_column"] ;
DateTime? instance = value != null && value is DateTime ? (DateTime?)value : (DateTime?)null ) ;
If the column returned is NULL, it will be returned as a System.DBNull, otherwise it will be returned as an instance of DateTime (or whatever the appropriate mapped type is — int, string, etc). Consequently, you need to check the type of object returned from the query before trying to cast it.
Looks like you are trying to call a method (dcdt.ToShortDateString()) on a DateTime? which doesn't have a value (it is, indeed, null). Try this:
dcdt.HasValue ? dcdt.ToShortDateString() : String.Empty;
EDIT (Just re-read the question): Also, don't try to convert to DateTime. Preserve the nullable.
EDIT #2 (based on comments):
Try this:
if (dcdt.HasValue)
{ userRow["DateCreated"] = dcdt.ToShortDateString(); }
else
{ userRow = DbNull.Value }
I saw that Dexter asked how he should go about it. Well, I would create an extension.
static class DateTimeExtensions
{
public static string ToString(this DateTime? dateTime, string format)
{
return dateTime.HasValue ? dateTime.Value.ToString(format) : String.Empty;
}
}
And then you can do:
DateTime? dt = null;
DateTime? dt2 = DateTime.Now;
Console.WriteLine(dt.ToString("dd-MM-yy"));
Console.WriteLine(dt2.ToString("dd-MM-yy"));
Note that I can call extension method on a nullable type if the object is null.
The problem is .NET null is not the same as SQL NULL. SQL Null is System.DBNull. So it is a [non-null] value in .NET.
Short answer
DateTime? dateTime = u.LastLogon?.ToShortDateString()

Can not convert int to string

I have this code:
int CityID= ((User)Session["LoggedInUser"]).CityID;
//When I debugg I get CityID = 7 here
ddlCity.Items.FindByValue(CityID).Selected = true;
And an error that I can not convert from int to string on the bottom line. How can I make it possibel?
FindByValue expects a string value so you have to convert CityID to a string.
Try this :
ddlCity.Items.FindByValue(CityID.ToString()).Selected = true
Parameter type should be string, not int, so just use built in ToString():
ddlCity.Items.FindByValue(CityID.ToString()).Selected = true;
MSDN: ListItemCollection.FindByValue() method
public ListItem FindByValue(
string value
)
Looks like FindByValue takes "String". Use CityId.ToString(CutureInfo.InvariantCulture) instead of CityId.
you will need to cast the integer to a string. This can be done in one of two ways
calling ToString() method
ddlCity.Items.FindByValue(CityID.ToString()).Selected = true;
This could raise a null reference exception if CityID is null.
Using ConvertToString()
ddlCity.Items.FindByValue(Convert.ToString(CityID)).Selected = true;
Also it is probably wise to check that the FindByValue method is not returning null as this will also cause a null reference exception when you attempt to set Selected = true

Categories

Resources