views:

370

answers:

3

Hello all,

I want to query a SharePoint list and want to use the data to be displayed in a usercontrol that I have created.

Earlier I had the data coming from a database.

Now I need to modify it to work with a SharePoint list.

Can you please guide me.

Grace.

+1  A: 
SPList list = null;
SPListItemCollection LIC = null;
SPListItem listItem = null;

using (SPSite mainSite = new SPSite("http://sitewhereyourlistis"))
{
    using (SPWeb mainWeb = mainSite.OpenWeb())
    {
     list = mainWeb.Lists["ListNameHere"];

     //**You will most likely want to limit your return to a single record so I have created the caml to do so with the List Item ID
     String caml = String.Format("<Where><Eq><FieldRef Name=\"ID\" /><Value Type=\"Counter\">{0}</Value></Eq></Where>", ListItemID);

     SPQuery qry = new SPQuery();
     qry.Query = caml;
     LIC = list.GetItems(qry);
     listItem = LIC[0];


     //**Here is where you will fill your textboxes
     txtTextBoxName.Text = listItem["ColumnNameHere"].toString();


     //**The above statement likes to error out if the value is null so I like to use a custom Application Helper Function to prevent things like this.
     //**My actual call to get the data would look like this.

     txtTextBoxName.Text = EnsureTextValue(listItem, "ColumnNameHere");
     // I added the Function Definition Below 

    }
}

public String EnsureTextValue(SPListItem item, String param)
{
    String tmp = String.Empty;
    try
    {
     tmp = item[param].ToString();
    }
    catch { "Run Debug Method or Whatever Here" }
    return tmp;
}

I am not sure if I missed anything but this should get you close.

Hope this helps!
20Seconds
Hi 20Seconds Thanks for your help. Can you please tell me how to edit the content in SharePoint list.
Pradeep007
A: 

I have used this to Query the SharePoint List

using (SPWeb web = SPContext.Current.Site.RootWeb) { SPList mylist = web.Lists["listName"]; SPQuery query = new SPQuery(); query.Query = "" + strXYZ+ ""; SPListItemCollection items = mylist.GetItems(query); tempDT = items.GetDataTable(); return tempDT; }

Pradeep007
A: 

To get Distinct Values for the column Click Here

To edit the values in the list there is a nice post here

Pradeep007