Check if discussion board item exists before creating

Hi,

I am creating a discussion board item programmatically using the below code:

    SPListItem discussionBoardItem = SPUtility.CreateNewDiscussion(spList, folderName);
 discussionBoardItem.Update();

The above code works, but does not check if the item exists. If the item exists, how to avoid creating it?

Thanks

September 10th, 2015 11:10am

Hi Venkatzeus,

From your description, you want to avoid creating the item if it exists in the discussion board.

You can get all items form the discussion board and then compare each of them with your folder name. If the name does not exist in the list, create the item.

Here is my code I have tested in my discussion board for your reference:

String folderName = "123";
Boolean isExisted = false;
using (SPSite site = new SPSite("http://sp"))
{
    using (SPWeb web = site.RootWeb)
    {
        SPList list = web.Lists["Discussion1"];
        if (list != null)
        {
            SPQuery query = new SPQuery();
            query.ViewFields = "<FieldRef Name='Title' />";
            SPListItemCollection itemColl = list.GetItems(query);
            foreach (SPListItem item in itemColl)
            {
                String subject = item["Title"].ToString();
                if(folderName == subject)
                {
                    isExisted = true;
                }
            }
            if(!isExisted)
            {
                SPListItem discussionBoardItem = SPUtility.CreateNewDiscussion(list, folderName);
                discussionBoardItem["Body"] = "What say you about task X?";
                discussionBoardItem.Update();
            }
        }
    }
}

Best regards,

Linda Zhang

Free Windows Admin Tool Kit Click here and download it now
September 11th, 2015 1:23am

This topic is archived. No further replies will be accepted.

Other recent topics Other recent topics