After adding mapped Layout folder in Visual WebPart project showing null reference error in Sharepoint 2010

sharepoint.stackexchange https://sharepoint.stackexchange.com/questions/176666

Question

I wanted to use css file to my visual WebPart. Developing it in VS2012. Initially worked fine without .css after deployment. After following steps here, updated the .wsp. It is also working fine. But when I am going to add same Web Part on another page it showing error as Object reference not set to an instance of an object In Code there is no null reference occurring while debugging.What should be the issue?

enter image description here Also verified the css file is properly generated at C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\TEMPLATE\LAYOUTS\1033\STYLES\MailSenderV2

Edited: After digging it out it is found that in debug mode (by attaching w3 processes), when I Edit page in Sharepoint site it hits the

 protected override void OnInit(EventArgs e)

Event of webpart and surprisingly it is making Page.Ispostback = true hence it is directly entering to the else part of condition.

if (!Page.IsPostBack)

And in this else part I am checked the value for drop down selected item. suddenly there is no values in drop down and returning null reference.Well I can change the logic here. But wondering why its making IsPostback as True in OnInit Event itself by hitting the Edit Page in Sharepoint site?

Was it helpful?

Solution

Let's see how the page should work.

When you select a web part in the Add Web Part gallery, a preview of the web part is displayed on the right panel (it would appear where the error message is). This means that SharePoint has to render a part of the web part to be able to display such preview - this is why the OnInit method is run.

As for the .IsPostBack check, let's consider how you got there in the first place. You selected a category on the left, a list of webparts was loaded and then you clicked on your custom one, only to get the error on the preview panel. I will have to double-check the actual code the oob page uses, but based on the end user experience, all of those click cause async partial page postbacks.So, since the web part control gets added to the panel on the left during an async partial postback, you are getting the "IsPostBack" branch of your code logic executed.

As you already stated, you can simply fix your logic to take this in account. But it may also be worthy to consider looking at the DisplayMode of the current WebPartManager component and use that info to bypass the normal web part logic when needed (see here for a somehow related example).

Licensed under: CC-BY-SA with attribution
Not affiliated with sharepoint.stackexchange
scroll top