Si8
Si8

Reputation: 9235

How to use EVAL to get the last four character of a string

I have the following code which displays some columns retrieved from a SQL query:

<tr class="trOther">
    <td><%# Eval("LastName").ToString() %></td>
    <td><%# Eval("FirstName").ToString() %></td>
    <td><%# Eval("SSN").ToString().Substring(Eval("SSN").ToString().Length - 4, 4) %></td>
    <td><asp:Button ID="btnGeneratePDF" ClientIDMode="Static" runat="server" Text="Generate PDF" CommandArgument='<%# Eval("LastName").ToString() + ", " + Eval("FirstName").ToString() %>' /></td>
</tr>

The SSN sometime is blank so in that case I would want it to display nothing, otherwise display the last four number of the SSN.

For example:

In 123-12-1234 it will display 1234

In 123121234 it will display 1234

In '' it will display '' (column doesn't have a value)

When I run the code I get the following error:

StartIndex cannot be less than zero

I am guessing it's because one of the entry it blank. How can I resolve it? (Maybe use a : and ? to emulate IF/ELSE statement in there?)

Upvotes: 0

Views: 1429

Answers (2)

Grax32
Grax32

Reputation: 4069

You could add an extension method such as the one below and call it like this <td><%# Eval("SSN").ToString().SafeSmartSubstring(-4,4) %></td>

    public static string SafeSmartSubstring(this string myString, int startIndex, int length)
    {
        var str = (myString ?? "").PadLeft(length);

        if (startIndex < 0)
        {
            startIndex = str.Length + startIndex;
        }

        return str.Substring(startIndex, length).Trim();
    }

Upvotes: 1

शेखर
शेखर

Reputation: 17614

You can use a below

<td><%# Eval("SSN").ToString().Length > 4 ?
    Eval("SSN").ToString().Substring(Eval("SSN").ToString().Length - 4, 4)
   :Eval("SSN").ToString() %></td>

Upvotes: 1

Related Questions