this.InstanceGUID returns all zeros

Novice User asked on December 14, 2017 23:30

Hi,

I am trying to build a widget and would like to create a unique id for my controls inside it. I want to use web part instance id to make it unique . In my code behind I am using these and they are either returned 00000000-0000-0000-0000-000000000000 or empty. What am I doing wrong?

I have tried all these variations.

wpID = this.WebPartID; // returns empty

wpID = this.InstanceGUID.ToString(); // returns 00000000-0000-0000-0000-000000000000

wpID = this.GetValue("WebPartControlID").ToString(); // returns Object reference not set to an instance of an object.

wpID = this.PartInstance.InstanceGUID.ToString(); //returns 00000000-0000-0000-0000-000000000000 

wpID = this.ID ; // returns empty

Thanks

Recent Answers


Hanh Dang answered on December 15, 2017 05:50

You can try this to generate a GUID

wpID = Guid.NewGuid().ToString();
0 votesVote for this answer Mark as a Correct answer

Novice User answered on December 15, 2017 16:26

I tried that as well but when two widgets are place on the same page, the below line is generating same GUIDs for both of the widgets. Same is the case with random numbers.

wpID = Guid.NewGuid().ToString();

Any other ideas are also welcome.

Thanks

0 votesVote for this answer Mark as a Correct answer

Hanh Dang answered on December 15, 2017 17:18 (last edited on December 15, 2017 17:22)

You should add a new property to the web part, then you can set the value for that property in SetupControl method. It worked correctly to me.

public string wpID
{
    get
    {
        return ValidationHelper.GetValue(GetValue("wpID"), "");
    }
    set { SetValue("wpID", value); }
}

protected void SetupControl()
{
    if (StopProcessing)
    {
        repItems.StopProcessing = true;
    }
    else
    {
        wpID = Guid.NewGuid().ToString();
        ...
    }
}

Or you can try this:

wpID = this.ClientID;
0 votesVote for this answer Mark as a Correct answer

   Please, sign in to be able to submit a new answer.