Take the 2-minute tour ×
SharePoint Stack Exchange is a question and answer site for SharePoint enthusiasts. It's 100% free, no registration required.

Is there a way to find the GUID from within a web part programmatically? For example, if there were two of the same web part added to the same page, is it possible to find the GUID of each of them from the code within the web part?

share|improve this question

3 Answers 3

up vote 3 down vote accepted

Typically when you want the ID from inside the web part, it is to ensure uniqueness in included client side script (since you might add the web part more than one time).

For this purpose, ID and ClientID works fine. If you need the GUID you could use string handling to remove the prefix.

   protected override void RenderContents(HtmlTextWriter writer)
    {
        base.RenderContents(writer);

        writer.Write("WebPart ID: {0}<br/>", this.ID);
        writer.Write("WebPart ClientID: {0}<br/>", this.ClientID);
    }

will render similar to this:

WebPart ID: g_4620e28f_2e09_49b9_9822_03bb3aa8b2b3 WebPart ClientID: ctl00_m_g_4620e28f_2e09_49b9_9822_03bb3aa8b2b3

This btw also the ID you will get from the web part manager:

WebPart1 myWebPart = (WebPart1)this.WebPartManager.FindControl(this.ID);
writer.Write("Webpart from WPM: ID: {0}", myWebPart.ID);

Webpart from WPM: ID: g_4620e28f_2e09_49b9_9822_03bb3aa8b2b3

share|improve this answer

There is usually a GUID attribute at the top of the Web Part class, if not, you can define one.

If two instances of the same web part are added to a page, they would obviously have the same GUID and thus you can't differentiate this way. It sounds like you'd need to use WebPartManager.

share|improve this answer

If you use Sharepoint Designer you should be able to get the webpart GUIDs easily.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.