.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
Sign In
Win Surprise Gifts!!!

Top 5 Contributors of the Month
Imran Ghani
Post New Web Links

ItemAdding Eventhandler

Posted By:      Posted Date: September 04, 2010    Points: 0   Category :SharePoint
Hi, i developed an ItemAdding Event handler. i want this eventhandler to be generic. i am trying to use this in the code, when debugged i get Object reference not set to an instance. can anyone help me in the right direction?             string siteUrl = properties.WebUrl;    //throws object reference not set to an instance here                          SPSecurity.RunWithElevatedPrivileges(delegate()             {                 using (SPSite CurrentSite = new SPSite(siteUrl))                 {                     using (SPWeb CurrentWeb = CurrentSite.OpenWeb())                     {                         SPList CurrentList = CurrentWeb.Lists[properties.ListId];      &

View Complete Post

More Related Resource Links

Redirecting to another page from an eventhandler on ItemAdding event

Hi,   I want to redirect to another page from an eventhandler on ItemAdding event. So please help me achieve in achieving this.    Thanks in Advance

Rejected by custom validation error & ItemAdding



I believe this topic was discussed before in this forum, but I couldn't find it using the exact error I receive: "operation for file.doc was rejected by custom validation on the server"

When I try to add a new word document to my doc library, Word displays this error instead of my custom error message. I set properties.Cancel=true in ItemAdding of my EventHandler, because my validation fails. 

Is there any way to display user properties.ErrorMessage instead of this generic error message?


how to get values of list item being entered in ItemAdding event handler?

Hi,          i am trying to get the values being entered in a listitem in the ItemAdding eventhandler as follows, but it doesnt work. public override void ItemAdding(SPItemEventProperties properties)         {             base.ItemAdding(properties);             SPSite CurrentSite = new SPSite("http://mm-moss/np/");             SPWeb CurrentWeb = properties.OpenWeb();             SPList CurrentList = CurrentWeb.Lists[properties.ListId];             string vehicleNo = CurrentList.Items[CurrentList.Items.Count - 1]["Vehicle No"].ToString();             string  name=CurrentList.Items[CurrentList.Items.Count-1]["Name"].ToString(); } when i debug i cant get hold of the VehicleNo value. canyone help me in getting the values of the list item being entered? Thank you all.

Search for Gridview on Eventhandler

Hello, I was woundering if there is a way to seach for a gridview on event handler.? I have three gridviews in which i can insert from and on my insertbutton codebehind, I want to check the gridview i am using so i could get the datakeynames for insert into the database. Does anyone have ideas. Thaks  

document library eventhandler (itemupdating & itemcheckedin) & winword infopanel issues

Hi all   I have eventhandlers  (itemupdating & itemcheckedin) which will fill few metadatafields (A,B) depending how one other (C)is set manually. All is going just fine in cases: - change C in datasheet view, - upload one & fill C - create new & fill C from document info panel & check in - open existin & change C from document infopanel & check in All updates to sharepoint goes just fine. After changing C and checking in, when I re-open the document in winword, the infopanel shows correct value in C, but old values in A and B (even thou sharepoint views show ok values in A and B after check in from winword)   Any best practises how the connection between infopanel and sharepoint should be dealt. I am suspectin that infopanel uses some cached values, and not refreshing data after eventhandler change metadata.   -heikki  

Restore from Recycle Bin - ItemAdding and Item Added

When restoring an item (specifically a document back to a document library) I need to be able to conditionally stop the restore from occuring. Let me tell you why... Say I have a doc lib with a custom column on. The column is of type datetime. The value in the column has to be unique. To do this I have an event receiver on itemupdating which runs a simple CAML query on the list to check that the value I provide is not being used elsewhere. If this test passes the update occurs, if not I do a properties.ErrorMessage="Column must contain a unique value" and a properties.Cancel=true. Simple. My problem is, say someone uploads a document, doc A, and gives it the date 01/01/2011. If I try and upload document B with the same date it will stop me - good. However if document A is deleted and I add my document B with 01/01/2011 it will allow that - still good as nothing in the doc lib has that date. The problem now would be if someone restored document A back to the library document A and B would both have the date 01/01/2011. Not good. I've had a look at the event receivers and the SPItemEventProperties object when a restore is performed and both adding and added fire. During adding there doesn't seem to be any of the original list item meta data available for me to interogate? During itemadded I can see the values on the SPListItem contained within the SPItemEventProper

EventHandler triggers another EventHandler

I have two EventHandlers - A and B. EventHandler A populates items in Child list, when Parent list creates a new item. Or vise versa, deletes items in Child list when Parent list deletes an item. There is a ParentID in Child list to refer back to ID column in Parent list. EventHandler B duplicates items from Site 1 to Site 2. i.e. creates a new item in Child list of Site 2, when Site 1 creates a new item in Child list. Or vise versa, deletes item in Child list in Site 2 when Site 1 deletes an item in Child list. The two Child lists are almost identical except Site 2 Child list has SourceID pointing back to ID column in Site 1 Child list ID field.   Site 1                                      Site 2 Parent    | EventHandler A    V Child   --- EventHandler B --->  Child   Now if I create/delete item in Parent list of Site 1, Child list of Site 2 will be affected, thanks to EventHandler A and B. Here A triggers B. If I create/delete item in Child list of Site 1, Child list of Site 2 will be affected as well, here only EventHandler B is triggered. My question is: Is there anyway to tell in EventHandler B, that it is triggered originally from Parent lis

EventHandler not working for survey item

Hi All,I'm quite new to sharepoint. Have tried a lot of search but couldn't get anything to work.I'm trying to make an eventhandling method to work in my sharepoint site. The code for the eventhandler is took from online itself:     RedirectSurvey   public class RedirectSurvey : SPItemEventReceiver {     public override void ItemAdding(SPItemEventProperties properties)     base.ItemAdding(properties);   SPList SahilSurvey = properties.OpenWeb().GetList("http://isvpoc3:14246/Lists/Sahil");   string currentResponse =   "Is Sahil a good boy?"].ToString();   if (currentResponse != "Yes")  {properties.ErrorMessage = "The only valid response is YES you nitwit!!";   true;     } }}} I build it and put the dll in GAC. Put the feature.xml and elements.xml in the feature folder.Activated the feature in the site.Elements.xml:     xml version="1.0" encoding="utf-8" ?>     Elements xmlns="http://schemas.microsoft.com/sharepoint/">     Receivers ListTemplateId="102">     Receiver>     Name>RedirectSurvey</Name>     Type>ItemAdding</Type>     SequenceNumber>20000</SequenceNumber>     Asse

ItemAdding event receiver - properties.ErrorMessage appears to be truncated


Hi there,

I have a MOSS Enterprise server with sp1 applied. I have a simple enough custom list with an event receiver. I have written some validation code in the ItemAdding event and I have code similar to the following:

if (!fieldsAreValid)
 properties.Cancel = true;
 properties.Status = SPEventReceiverStatus.CancelWithError;
 properties.ErrorMessage = errorMessage;    

I have a web part that adds items to the custom list, in the web part I have some code which catches the SPException thrown afer calling SPListItem.Update(), within the catch block for the SPException I then retrieve the SPException.Message property and display to the user.

My problem is that I was assuming that the properties.ErrorMessage from the event receiver would be what is used to populate the SPException.Message property - in my case I am getting am SPException.Message property with only the first random amount of characters from the properties.ErrorMessage property.

Looking at reflector and the call stack in Visual Studio there appears to be an unmanaged/managed transition to the Microsoft.SharePoint.Library.SPRequestInternal class in the Microsoft.SharePoint.Library in the OWSSvrLib.dll file so I cannot find the point at which the string is truncated but I would at least li

EventHandler Firing only for administrator users



I have wrote an event handler which is working very good.

Today I finally tested it using a non administrator user and the event handler is just not firing (it ignore the code).


My code start like this:

public override void ItemAdding(SPItemEventProperties properties)

            StreamWriter sw = File.CreateText("c:\\splog.txt");
            sw.WriteLine("Code Ran");
            SPSite spSite = new SPSite("http://sharepoint");
            SPWeb web = spSite.OpenWeb("/");



When I use an administrator account I can see the file created and got no problem, when I use a non administrator account the code is just not running.

Thank you very much for any help.

ItemAdding event receiver has missing lookup information in afterproperties



I am working on a little event receiver for a custom list. I noticed that afterproperties for lookup fields only contain the index but NOT the value of the lookup field. This is only the case for single selection fields. Multiple selection lookup fields will carry all index and value information for all selected fields. This means for multi-selection fields you can use SPFieldLookupValueCollection to iterate and SPFieldLookupValue to access index and value separately. If you try using SPFieldLookupValue on single-select lookup fields, - because the afterproperty is incomplete -  you will receive an error message: Unknown Status Module: 33 Message: 134

The question is: Can this behavior be confirmed and is it limited to the "ItemAdding" event? Thank you very much... 


public override

GridView -> ItemTemplate EventHandler setzen


Hi all,


i have a dynamically created GridView with a CheckBox by means of TemplateField.ItemTemplate. Now i want to add an EventHandler (CheckedChanged) on it. Is this possible?

          TemplateField tempField = new TemplateField();
          itemplateCheckBox chb = new itemplateCheckBox(dc_.ColumnName, GridView2);
          tempField.ItemTemplate = chb;
          tempField.HeaderText = dc_.ColumnName;


    public void InstantiateIn(Control container)
      CheckBox cb = new CheckBox();
      cb.DataBinding += new EventHandler(this.bindBooleans);
      cb.CheckedChanged += new EventHandler(this.checkBoxChanged);



Itemadding or Itemupdating related messages.


Within Itemadding or Itemupdating, we check for any validations etc and if there is something incorrect/wrong we will set below lines and users will get to see the message. That is fine but the two other links such as below makes user to deviate or give an option navigate to elsewhere. Sometimes the USERS will not be knowing that it is sharepoint based site but the links below clearly states that.

So I want to know if there is a way to get rid of the below links. Any other suggestion or best practices please suggest.

Go back to site

Troubleshoot issues with Windows SharePoint Services.


TreeView EventHandler


Hi all. I have a problem with adding an EventHandler to the TreeView control. TreeView is added to form dynamically.

When I click on a tree node nothing happens.

Help me to solve this problem. 

Here part of class that generates treeview:


 public class Menu_constructour
 public void generate_tree(PlaceHolder field)
 TreeView tree = new TreeView();
            tree.ID = "tree";

WebForm1 web = new WebForm1(); tree.SelectedNodeChanged += new EventHandler(web.tree_SelectedNodeChanged); tree.PopulateNodesFromClient = true; TreeNode node1 = new TreeNode(); node1.Text = "Parent node1"; TreeNode _node11 = new TreeNode(); _node11.Text = "Child node"; TreeNode _node12 = new TreeNode(); _node12.Text = "Child node2"; TreeNode node2 = new TreeNode(); node2.Text = "Parent node2"; node1.ChildNodes.Add(_node11); node1.ChildNodes.Add(_node12); tree.Nodes.Add(node1); tree.Nodes.Add(node2); // ????????? ?????? ?? ???????? field.Controls.Add(tree); } }


Need to find the actual URL in itemadding or itemupdating.


I have couple of customized copies of NewForm.aspx & EditForm.aspx. These copies have ASPX page such as NewTasks.aspx, EditTasks.aspx. These two ASPX pages along with NewForm.aspx, EditForm.aspx are operational.

Now what I am trying to do is in itemadding & itemupdating (also itemadded/itemupdated) I need to check the actual page that the user has used such that I can decide which columns to update based on the actual page that user used.

However it looks the httpcontext or spcontext is returning Null to me.

Tried to follow this link but no luck so far.


Please suggest.

Using the AfterProperties on ItemAdding on a Document Library?


Hi, I'm trying to programmatically set a document's "Name" and "Title" in the event ItemAdding. Can anyone tell me why the code below is not working? There are no errors/exceptions, it just doesn't work?

        public override void ItemAdding(SPItemEventProperties properties)
            string titleInternalName = "";
            string nameInternalName = "";

            using (SPWeb web = properties.OpenWeb())
                titleInternalName = web.Lists[properties.ListId].Fields["Title"].InternalName;
                nameInternalName = web.Lists[properties.ListId].Fields["Name"].InternalName;

            string text = "HelloWorld";
            properties.AfterProperties[titleInternalName] = text;
            properties.AfterProperties[nameInternalName] = text;


How to show html tags in Properties.Errormessage in Itemadding, Itemupdating?

    properties.Cancel = true;
    properties.ErrorMessage = "You are yet to choose an answer . <a href='" + cUrl + "/lists/hire/Emp.aspx" + "'> <u>Click</u></a> here to define now<br>";

In the above examples (within ItemAdding), the error message is shown but it doesn't show the actual hyperlink itself. It shows everything including the <a> and </a> tags.

Is there anything to set anywhere else to show the html tags.

ASP.NetWindows Application  .NET Framework  C#  VB.Net  ADO.Net  
Sql Server  SharePoint  Silverlight  Others  All   

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend