How to begin with making a custom web part in Visual Studio, collecting data from lists across different sites?
-
10-12-2019 - |
Question
First of all I'd like to say that I'm very new at working with Visual Studio 2013 and with C# as well.
I want to make a certain web part in Visual Studio 2013 for a SharePoint 2013 test environment. The web part needs to fetch list items from different announcement lists, these announcement lists can be on different sites. Basically I need to be able to show the content of all those announcement lists into one custom list.
Here's an example of the scenario:
Subsite A: has a list named "List X"
Subsite B: has a list named "List Y"
Subsite C: has a custom web part that shows items from "List X" and "List Y"
So I want to make a custom web part in Visual Studio that will be placed on subsite C, which will show items from other lists located on other subsites.
I can deploy to our test environment and I can add a custom web part to a page so I got that going for me which is nice, but I just need a little push.
Some suggestions on what I might need (from the toolbox perhaps) or how I can get data from those SharePoint lists (suggestions, links, anything), that would all be very welcome.
Your help and time is greatly appreciated!
Solution
You can use SPSiteDataQuery for getting List data from multiple sub sites of same site collection.
Below is the basic code to start with ,bywhich you can use to get all announcement list items from the different sub sites:
using (SPSite oSPsite = new SPSite(SPContext.Current.Web.Url))
{
using (SPWeb oSPWeb = oSPsite.OpenWeb())
{
// Fetch using SPSiteDataQuery
SPSiteDataQuery query = new SPSiteDataQuery();
query.Lists = "<Lists ServerTemplate=\"104\" />";//104=List template ID for "Anouncements"
query.ViewFields = "<FieldRef Name=\"Title\" />";//Add other fields which you want to get.
query.Query = "";//you can add your caml query if you want to filter the list items returned
query.Webs = "<Webs Scope=\"SiteCollection\" />";//Scope is set to site collection to get data from all anouncement lists in that site collection.
DataTable dataTable = oSPWeb.GetSiteData(query);
}
}