简体   繁体   中英

Format a label in a gridview to hide first 5 digits of a social security number

I have a data-bound label inside a template field of a griview that displays Social Security Numbers. It currently shows the SSN's as such, 123-45-6789. I need to hide the first 5 digits so it show's like ###-##-6789. Does anyone have an example of how I might accomplish this.

Here is the mark-up for the template fied:

    <asp:TemplateField HeaderText="Social Security Number" SortExpression="SSN">
         <ItemTemplate>
              <asp:Label ID="lblSSN" runat="server" Text='<%# Bind("SSN") %>'></asp:Label>
         </ItemTemplate>
    </asp:TemplateField>

Code block that adds decrypted SSN to grid:

    table.Columns.Add("SSN");
            foreach (DataRow row in table.Rows)
            {
                row["SSN"] = DecryptSSN(row["EncryptedSSN"].ToString());                   
                row.AcceptChanges();
            }

I'm new to programming so any help would be greatly appreciated.

Here is a helper method.

public static string GetMaskedNumber(string number)
{
    if (String.IsNullOrEmpty(number))
        return string.Empty;

    if (number.Length <= 5)
        return number;

    string last5 = number.Substring(number.Length - 5, 5);
    var maskedChars = new StringBuilder();
    for (int i = 0; i < number.Length - 5; i++)
    {
        maskedChars.Append(number[i] == '-' ? "-" : "#");
    }
    return maskedChars + last5;
}

Result

123-123-1234 to ###-##-1234

Use this and replace row["SSN"] the code below you can use to test it's functionality so something like this would work if the value were "123-45-6789"

foreach (DataRow row in table.Rows)
{
    var newMaskedSSN = DecryptSSN(row["EncryptedSSN"].ToString().Replace("-", string.Empty)); 
    if (newMaskedSSN.Length > 4)
    {
        Console.WriteLine(
            string.Concat(
               "".PadLeft(9, '*'), 
        newMaskedSSN.Substring(newMaskedSSN.Length - 4)));
        row["SSN"] = newMaskedSSN; 
        row.AcceptChanges();
    }
}

results: *****6789

这个怎么样?

  select '###-##-'+right(ssn_coumn,4) as ssn  from your_table 

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM