How to check null for the null value from DB in DataSource

Hi Team,

Getting error in .NET code while null value in word template for following code.
Key.SelectedDevices.ToString().Replace(", ","\r\n")].
Here Key.SelectedDevices is getting null value from DB as per the configuration.

By Using << if [Key.SelectedDevices!= null]>><<[Key.SelectedDevices.ToString().Replace(“, “,“\r\n”)]>><</if>> still it’s showing exception.
Could you please help to resolve this error.

Thanks

@SonalCR

To handle null values in your .NET code when working with a Word template, you can use a conditional check to avoid exceptions. It seems you are trying to replace a null value in Key.SelectedDevices with a formatted string.

Here’s a recommended approach:

  1. Check for null: Before calling ToString() on Key.SelectedDevices, ensure that it is not null.
  2. Use a conditional operator: You can use the null-coalescing operator (??) to provide a default value if Key.SelectedDevices is null.

Here’s an example of how you can implement this:

string selectedDevices = Key.SelectedDevices ?? string.Empty; // Use an empty string if null
string formattedDevices = selectedDevices.Replace(", ", "\r\n");

In this code:

  • If Key.SelectedDevices is null, it will default to an empty string, preventing any exceptions when calling Replace().
  • The Replace method will then format the string as needed.

If you are using a template with conditional statements, ensure that the logic correctly handles the null case. For example:

<< if [Key.SelectedDevices != null]>>
    <<[Key.SelectedDevices.ToString().Replace(", ", "\r\n")]>>
<</if>>

Make sure that the condition checks for null before attempting to access properties or methods on Key.SelectedDevices. This should help you avoid exceptions related to null values.

If you continue to experience issues, please provide more details about the specific error message you are encountering, and I can assist you further.

@SonalCR In your case you can use the following syntax:

<<var [val=Key.SelectedDevices==null?””:Key.SelectedDevices.ToString()]>>
<<[val.Replace(",","\r\n")]>>

Hi @alexey.noskov , Thanks it’s working.

1 Like