I want to get the width and height in px of my webpart, however, it shows an error as shown below.

An object reference is required for the non-static field, method, or property 'Microsoft.SharePoint.WebPartPages.WebPart.Width.get'

Do anyone know what how can i fix it?

my code:

string width= Microsoft.SharePoint.WebPartPages.WebPart.Width;

You need to first get an instance of the particular webpart, you are trying to find the dimensions of.

using (SPSite spSite = new SPSite("SiteURL")
  using (SPWeb spWeb = spSite.OpenWeb())
    SPWebPartCollection webparts = spWeb.GetWebPartCollection("WebPageURL", Storage.Shared);

    for (int k = 0; k < webparts.Count; k++)
      //get reference to webpart
      Microsoft.SharePoint.WebPartPages.WebPart wp = webparts[k];

      //check webpart Title to find webpart whose value is to be changed
      if (wp.Title == "MyWebpartTitle")
        //get width and height property values of the webpart object
        string strWpWidth = wp.Width;
        string strWpHeight = wp.Height;

MSDN WebPart.Height property

MSDN WebPart.Width property

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.