Reputation: 1666
So I have a tab delimited file that I need to insert through sqlbulkinsert. I have all my code written and working properly, but when I reach a value that is assigned an integer or decimal without a value inputted, my code breaks because the assignment is incorrect (a null to a decimal value)... How can I handle this?
dataRow["variableName"] = splitString[IndexValue]; // decimal coming in blank because this column doesn't have a decimal assigned (and not required)
Thanks!
Edit: I do know I can test the value for null before assignment, but would prefer not using an if check if there's another way to cast this.
Ended up using the ternary operator.
dataRow["variableName"] = (String.IsNullOrEmpty(splitString[IndexValue])) ? Convert.ToInt32(splitString) : 0;
Upvotes: 2
Views: 3793
Reputation: 33183
Do a simple check before the assignment:
if (varT != null)
//perform assignment
else
Change varT to the name of the value you are checking against. Also you need to tell us what is null and what isn't it is hard to tell with the content of your question. Is splitString[IndexValue] null or the datarow?
Per your comment you can make use of the conditional operator:
return varT != null ? varT : 1.0;
Or as others have mentioned you can use the ??
operator http://msdn.microsoft.com/en-us/library/ms173224.aspx
Upvotes: 1
Reputation: 1863
You can avoid this issue with the following code:
if (splitString[IndexValue] != null)
dataRow["variableName"] = splitString[IndexValue];
Upvotes: 0