Friday, January 16, 2009

Retrieving a Person's Last Name from a FullName field

I encountered a unique situation where a client's database table had usernames stored in a single "FullName" field, rather than the more common approach of having one field for the first name and another field for the last name. Restrictions within the company prevent this from ever being altered. Yet I needed a way to retrieve a person's last name, no matter how a name might be formatted.

Based on the possible data in their database, I wrote this code to accomplish this:

// A string containing a person's full name comes in 3 forms:
// 1. John Smith
// 2. John O. Smith
// 3. Smith, John [O.]
// This method returns just the last name.
public static string GetLastName(string fullName)
string lastName = "";
fullName = fullName.Trim();

if (fullName.Contains(",")) // Case #3
int idx = fullName.IndexOf(",");
lastName = fullName.Substring(0, idx);
int idx = fullName.IndexOf(" "); // Find the first space character
int idx2 = -1;
if (idx != -1)
idx2 = fullName.IndexOf(" ", idx + 1);

if (idx2 != -1) // Case #2
lastName = fullName.Substring(idx2 + 1);
else // Case #1
lastName = fullName.Substring(idx + 1);

return lastName;

How to Expand/Collapse a TreeView with Javascript

I encountered a task today that I thought would be extremely simple: Add a button that would expand/collapse a treeview in a toggle-like manner:

But after I implemented my code, it kept getting stuck on "Expand All". The reason turned out to be that the button was forcing a partial postback in the AJAX Update Panel, even though I had no server-side event defined.

The solution was to modify the client-side click definition a little:

OnClientClick="buttonExpandCollapse_Click(); return false;" />

If you don't add the "return false;" addendum then a postback occurs.

Here by the way is the Javascript code that this button calls:

var treeExpanded;
function buttonExpandCollapse_Click()
if (treeExpanded == null)
treeExpanded = false;

var button = $get('<%= buttonExpandCollapse.ClientID %>');
var treeView = <%= treeViewMain.ClientID %>;

// TreeView expand/collapse code here; varies depending on the type of treeview control

if (treeExpanded)
button.value = 'Expand All';
button.value = 'Collapse All';

treeExpanded = !treeExpanded;