1

I am new to SharePoint and am wanting to query a SharePoint site and return data to a C# windows form. This is my scenario I have a text box where a user can input a ICDN number, then press a button. I want to then run a select statement against the SharePoint site and

Select firstname, lastname, address, city, state, zip from sharepointlist where ICDN = textbox1.Text;

And populate corresponding textboxes on the windows forms with the returned values like such

textboxfname = firstname;
textboxlname = lastname;
textboxcity = city;
textboxstate = state;
textboxzip = zip;

Of course this is rough pseudocode, but the question at hand is how to query a specific field name from your sharepoint site?

1

Please try the following code. Make sure you're using Microsoft.SharePoint namespace.

string siteUrl = "http://mysharepointsite";
string webUrl = "/accounting";
string listName = "Data List";

// Use the site
using (SPSite site = new SPSite(siteUrl))
{
    // Use the web
    using (SPWeb web = site.OpenWeb(webUrl))
    {
        // Get the list
        SPList list = web.Lists.TryGetList(listName);
        // Create our query
        SPQuery query = new SPQuery();
        // Set the query string
        query.Query = string.Concat(
            "<Where><Eq>",
                "<FieldRef Name='ICDN'/>",
                "<Value Type='Text'>",
                    textbox1.Text,
                "</Value>",
            "</Eq></Where>",
            "<OrderBy>",
                "<FieldRef Name='Created' Ascending='TRUE' />",
            "</OrderBy>");
        // Select our fields
        query.ViewFields = string.Concat(
            "<FieldRef Name='firstname' />",
            "<FieldRef Name='lastname' />",
            "<FieldRef Name='address' />",
            "<FieldRef Name='city' />",
            "<FieldRef Name='state' />",
            "<FieldRef Name='zip' />");
        // Get only the data that we need.
        query.ViewFieldsOnly = true;
        // Fetch items
        SPListItemCollection items = list.GetItems(query);
        // Get first item
        SPItem item = items[0];
        // Assign our values
        textboxfname = Convert.ToString(item["firstname"]);
        textboxlname = Convert.ToString(item["lastname"]);
        textboxcity = Convert.ToString(item["city"]);
        textboxstate = Convert.ToString(item["state"]);
        textboxzip = Convert.ToString(item["zip"]);
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.