Sunday, February 5, 2012

Using SPQuery to return SharePoint list items

Using SPQuery and CAML(Collaborative Application Markup Language) is an efficient way to retrieve data in SharePoint list. It help us to filter and order items in the selected list.
In this post, I want to introduce to you an example of using them.
In the following code, I want to get all the employees with the position of Developer in Employee list, then, I order them by their Salary ascending.

            SPWeb web = SPContext.Current.Web;
            SPList list = web.Lists["Employee"];
            string query = @"<Where>
                                              <Eq>
                                                    <FieldRef Name='Position' /><Value Type='Choice'>{0}</Value>
                                             </Eq>
                                   </Where>
                                   <OrderBy>
                                            <FieldRef Name='Salary' Ascending='False' />
                                   </OrderBy>";
            query = string.Format(query, "Developer");                                                           
            SPQuery spQuery = new SPQuery();
            spQuery.Query = query;
            SPListItemCollection items = list.GetItems(spQuery);
            grid.DataSource = items.GetDataTable();
            grid.DataBind();

Result:



Hope this helps!

0 comments:

Post a Comment

Twitter Delicious Facebook Digg Stumbleupon Favorites More

 
Design by Free WordPress Themes | Bloggerized by Lasantha - Premium Blogger Themes | Affiliate Network Reviews