i am inserting a value from datarow to access database and if the row[1] value is blank it throws an error Data type mismatch in criteria expression and if value is there it insert properly. what i am missing here. in access the column1 is of type Number.
string SNumber = row[1].ToString();
if (SNumber.ToString() != null)
{
if (SNumber .ToString() != "")
{
SNumber = row[1].ToString();
}
else
{
SNumber = "NULL";
SNumber = DBNull.Value.ToString();
}
}
insert into table1 (Column1) values (SNumber);
I guess, if row[1] is null then you will receive an exception too. if row[1] can return a nullable datatype (which is not clear in your question) then maybe you should replace:
string SNumber = row[1].ToString();
with
Number SNumber = row[1];
and then replace your outer if-statement with:
if (!string.IsNullOrWhiteSpace(SNumber.ToString())) {
[..]
}
There may be possibility that the row value is blank or may be null. So only checking null is not sufficient, you have to check for both null then an empty sting as blank is not allowed for Number datatypes.
May be you can use string.IsNullOrEmpty
try this
if (!string.IsNullOrEmpty(row[1].ToString())
{
// do your stuff
}
You can replace all of your code with a ternary operator:
string query = "insert into table1 (Column1) values (" +
((row[1] != null && row[1].ToString() != String.Empty)
? row[1].ToString()
: null)
+ ") etc... etc...";
if I understand what you want correctly. If row[1] is null or empty, insert null. Else insert row[1]'s value.
Ok, I suppose Column1
is a numeric field. And then if you try to insert string it will throws an error, because
SNumber = "NULL";
is a String . If it was:
SNumber = NULL;
then this will be a null value. But maybe it will be better to use Nullable int - Nullable types MSDN
int? num = null;
The question mark point that it can hold also a NULL
value. Hope this helps.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.