Question

I have built a custom visual web part in c# for SharePoint 2010. What I would like to do is be able to query a specific list in SharePoint and then process the results. I am a complete noob when it comes to SharePoint (but do have extensive experience developing Drupal solutions). I can create a query string no problem:

SELECT 'GenericName' FROM 'MyTable' WHERE 'GenericName' LIKE 'something%' 

My question is how do I set up my web part to process the query? I assume there must be some boilerplate code that accomplishes this as this must be a fairly common operation. I have seen the following code:

SearchServiceApplicationProxy proxy = (SearchServiceApplicationProxy)SearchServiceApplicationProxy.GetProxy
   (SPServiceContext.GetContext(SPContext.Current.Site));
        KeywordQuery query = new KeywordQuery(proxy);
        query.ResultsProvider = Microsoft.Office.Server.Search.Query.SearchProvider.Default;
        query.QueryText = queryText;
        query.ResultTypes |= ResultType.RelevantResults;
        ResultTableCollection searchResults = query.Execute();

However, I think this code is for accessing SharePoint's default search page and not targeting a specific list (but maybe I am wrong about that).

Can anyone tell me what I need to do with some code examples?

Thanks.

Était-ce utile?

La solution

  1. In SharePoint querying of lists is done using CAML query instead of SQL queries. Tools like CAML Query Helper and U2U CAML Query builder can be used to generate your query and to test it.

  2. Check this post on creating Visual Webparts for SharePoint 2010

  3. Now you can use below code as a starting point for reading data from list.

using (SPSite site = new SPSite(SPContext.Current.Web.URL)) {
using (SPWeb web = site.OpenWeb())
{
    // choose the list
    SPList list = web.Lists.TryGetList("insert your list Name");
    if(list!=null)
    {
        SPQuery myquery = new SPQuery();
        myquery.RowLimit = 6;//if you want to limit number of items returned. Comment if not required.
        myquery.Query = "Your Caml query here";

        SPListItemCollection items = list.GetItems(myquery);

        foreach (SPListItem item in items)
        {
            // check the item for null
            if (item != null)
            {
                // do something
            }
        }
    }
} }
Licencié sous: CC-BY-SA avec attribution
Non affilié à sharepoint.stackexchange
scroll top