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;
}
Published Thursday, July 05, 2007 11:14 PM by Palermo4
Filed under: , , ,

Comments

# re: Getting the Friendly Control ID

Friday, July 06, 2007 12:12 AM by Chua Wen Ching

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.

# re: Getting the Friendly Control ID

Friday, July 06, 2007 3:23 AM by Japi

works fine :)

another implementation could be:

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

return parts[parts.Length - 1];

# re: Getting the Friendly Control ID

Friday, July 06, 2007 10:37 AM by Palermo4

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.  

# re: Getting the Friendly Control ID

Friday, July 06, 2007 10:40 AM by Palermo4

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 :)

# re: Getting the Friendly Control ID

Sunday, July 08, 2007 9:57 PM by Chua Wen Ching

I see. :) Thanks for the info.

# Revision: Get the Value of a Control Without an Instance of the Control

Friday, July 20, 2007 3:40 PM by Community Blogs

On an earlier post, I provided code that would retrieve the value of a control from the HTTP post without

Leave a Comment

(required) 
(required) 
(optional)
(required)