Search code examples
sharepointsharepoint-2007

How to edit and read data in a SharePoint List


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.


Solution

  • 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 it helps!