Getting the Friendly Control ID

Here is a simple utility method that will take a string argument such as  
"ctl00$ContentPlaceHolder1$DropDownList1" and return "DropDownList1"

public static string GetFriendlyControlId(string renderedControlId)
{
    // PageIdSeparator is a property returning Page.IdSeparator
    int indexOfSeparator = renderedControlId.LastIndexOf(PageIdSeparator);
    if (indexOfSeparator >= 0)
    {
        renderedControlId = renderedControlId.Substring(indexOfSeparator + 1);
    }
    return renderedControlId;
}

5 Comments

  • Hi,

    In fact if you want to get the exact id of a control, you can do this:
    Response.Write(TextBox1.ID);

    It will just work you know. Thanks.

  • works fine :)

    another implementation could be:

    string[] parts = renderedControlId.Split(PageIdSeparator.ToCharArray());

    return parts[parts.Length - 1];

  • Chua Wen,

    Although you are correct, there are times we need to access the value of the control before the control instance is available. For example, if I needed to know the value of any control while in HTTP pipeline events preceeding the Handler processing (such as Begin_Request event). Or even in the early stages of page processing, such as the InitializeCulture override.

  • Japi,

    Although your suggested implementation works, it introduces the need to create two arrays to accomplish the task. I believe my implementation does not introduce as much overhead. Nonetheless, thanks for the feedback :)

  • I see. :) Thanks for the info.

Comments have been disabled for this content.