eyalb
eyalb

Reputation: 3022

Convert bool? to Yes/No/null string

i have an object that as a parameter bool?

i need to show it on a repeater.

<%# Eval("LS_Body_Connection") %>

i create a class

public static class BooleanExtensions
{
    public static string ToYesNoString(this bool value)
    {
        return value ? Resources.Yes : Resources.No;
    }
}

how to use it on the repeater?

i try

((bool)Eval("LS_Body_Connection")).ToYesNoString()

but it's not recognaize

'bool' does not contain a definition for 'ToYesNoString' and no extension method 'ToYesNoString' accepting a first argument of type 'bool' could be found (are you missing a using directive or an assembly reference?)

in the cs of the page i can call the extension method

when i add

<%@ Import Namespace="IDD.App_Code" %>

i get The call is ambiguous between the following methods or properties: 'IDD.App_Code.BooleanExtensions.ToYesNoString(bool?)' and 'IDD.App_Code.BooleanExtensions.ToYesNoString(bool?)'

Upvotes: 2

Views: 3426

Answers (3)

Damith
Damith

Reputation: 63065

try ((bool)Eval("LS_Body_Connection")).ToYesNoString()

And you need to import the namespace like below as Claudio's Answer

<%@ Import Namespace="My.Namespace.Containing.MyExtensions.Class" %>

Upvotes: 5

Claudio Redi
Claudio Redi

Reputation: 68400

Try adding inporting the namespace where the extension method is placed

<%@ Import Namespace="YourNameSpace" %>

You'll also need to cast the Eval return value to bool as @Damith explained.

Upvotes: 3

Rawling
Rawling

Reputation: 50114

Firstly, you'll need a version of ToYesNoString that accepts a bool?, rather than just bool, parameter.

public static string ToYesNoString(this bool? value)
{
    return value.HasValue ? ToYesNoString(value.Value) : null;
}

Then in your repeater, you should be able to cast the result of Eval to a bool?

(bool?)Eval("LS_Body_Connection")

and then either call the extension against it

((bool?)Eval("LS_Body_Connection")).ToYesNoString()

or, if that doesn't work, call the method explicitly

BooleanExtensions.ToYesNoString((bool?)Eval("LS_Body_Connection"))

Upvotes: 2

Related Questions