none
Get data from a SPListItem and place it in a WebPart

    Question

  • Hi all,

    What I want to do is very simple. I've created a custom list in WSS and I want to get the information contained in this list to place it in a C# WebPart that I've coded.
    The information will be received when I click on a button on my WebPart.

    The real issue is : how can I get the SPListItem and work on it ?

    This is the beginning of the code of my button, that doesn't work :

    private void button_Clic(object sender, EventArgs e)
    {
         this.EnsureChildControls();

         SPSite MySite = new SPSite(SPContext.Current.Site.Url);
         SPWeb CurrentSite = MySite.OpenWeb();

         SPList MyList = SPContext.Current.Web.Lists["TheNameOfMyList"];
         SPListItem TheItem = MyList.Items["TheNameOfMyItemInWSS"];

         (...)
    }

    The trouble is on Items["TheNameOfMyItemInWSS"] : it must be a Guid in the []...
     
    How can I get this number ? Is there another solution to open TheItem and work on it ?

    Thanks in advance for your help !

          
        
    Thursday, August 21, 2008 9:51 AM

All replies

  • You should query the list using a CAML query. There's an example on how to do this here

    Einar Otto Stangvik | http://einaros.blogspot.com | Remember to close your threads :-)
    Thursday, August 21, 2008 10:27 AM
  • Hi, thanks for your answer,
     
    I'm sorry but I think I don't understand very well the example...

    In the case of my button, should it be something like this ?

    private void button_Clic(object sender, EventArgs e)
    {
         this.EnsureChildControls();

         SPSite MySite = new SPSite(SPContext.Current.Site.Url);
         SPWeb CurrentSite = MySite.OpenWeb();

         SPList MyList = SPContext.Current.Web.Lists["TheNameOfMyList"];
         SPQuery quer = new SPQuery(MyList.DefaultView);
         quer.Query = "<Where><Eq><FieldRef Name = 'AField'/><ValueType='Text'>ValueOfTheField</Value</Eq></Where>";

         SPListItemCollection items = MyList.GetItems(quer);

         foreach (SPListItem item in items)
         {
               item["AField"] = "AnotherValueForTheField";
         }
    }

    If I understand the example well, this code is supposed to change every FieldValue of the items in the item collection.
    But it doesn't work... 

    Please help !
        
    Thursday, August 21, 2008 11:53 AM
  • Shine76,

    A few things.

    1 - SPList MyList = SPContext.Current.Web.Lists["TheNameOfMyList"] should really be SPList MyList = CurrentSite.Lists["TheNameOfMyList"].  You are needlessly creating an additional SPWeb.
    2 - You should wrap your SPSite AND your SPWeb into using statements so that they get disposed of properly.  As the code stands now they will leak memory.
    3 - To solve your immediate problem, you need to call item.Update() inside your loop for the update to actually happen.
    4 - This will only work if the person running the code has permission to update the items.

    Hope this helps,

    Dan
    http://devcow.com/blogs/jdattis/
    Thursday, August 21, 2008 1:05 PM
  • Hi, thanks for your answer, you're right, my code is better like that...

    I've tried to put item.Update(); in my loop foreach, but it still doesn't work. Always the same error in WSS : 

    "One or several types of fields are not installed correctly. Go to the settings page list to remove those fields." (translated from French with Google...)

    What is that error refering to precisely according to you ?
    Thursday, August 21, 2008 1:22 PM
  • Shine76,

    I would guess that the filed you are updating is being referenced incorrectly.  For example, you may need to refer to it by its internal name as ipposed to its display name.

    Also, verify that the field is in the fields collection before updating it and that the data type you are updating it with matches the data type of the field.

    Hope this helps,

    Dan


    http://devcow.com/blogs/jdattis/
    Thursday, August 21, 2008 2:11 PM
  • Yes, it works with the internal name, thanls.

    But when the items are selected, there are errors when I try to do :

    private void button_Clic(object sender, EventArgs e)
    {
         this.EnsureChildControls();

         [the previous code]

        foreach (SPListItem item in items)
         {
               if( (string)item["AField"] == "AText" )
               {
                    WebPartTextBox.Text = (string)item["AField"]; 
                }     
         }
    }

        What I want to do is collecting information from the items and place them in WebControls of a WebPart. The code in Bold doesn't work...
    • Edited by Shine76 Friday, August 22, 2008 8:46 AM Code error
    Friday, August 22, 2008 8:45 AM
  • Before that check if your SPListItemCollection object 'items' is getting all the list items, might be the case that it is not getting 'filled-up'.

    -xwindow
    • Edited by xwindow Friday, August 22, 2008 10:05 AM modification
    Friday, August 22, 2008 10:05 AM
  • Yes, I can confirm that my SPListItemCollection is getting all the items of my list.

    It's in the 'IF' condition in my code in bolt that there is a problem. Maybe there is a missing symbol but I don't konw which one...
    Friday, August 22, 2008 11:19 AM
  • OK, there can be various reasons why this is not coming in the textbox.

    Are you getting any error when you click the button? are you able to see the textbox in the webpart? Is the page posting back when you click the button?

    It's very difficult to understand, will be better if you can give us the whole (exact code) and tell us what is the exact scenario that you are facing, along with any error message (if you are getting one).

    -xwindow
    Friday, August 22, 2008 11:38 AM
  • When I click the button, there is a classic "Error" screen (with no more precisions) in SharePoint, so that the page is not posting back...
    I can see the TextBox in my WebPart.

    This is the scenario :

    -> I have programmed a WebPart, that is a kind of "formular", with more than 100 WebControls (Labels, TextBox, CheckBoxLists, CheckBox, Buttons).
    -> I want to use in WSS the information written by the user in my WebPart. So I've programmed a button that gets the information of the WebPart and place it in a Custom List.
    -> Now, the custom list is not easy to read for the users (too much data). Consequently, because my WebPart has a much better presentation,  I want to code another button which will do the contrary : get the information of my custom list and put it in my WebPart. This button is necessary for the visibility of these informations.

    I will not give you the whole WebPart class code, since it's already a 2000 lines code. But this is the structure :

    (usings)

    (initialisation of the WebControls)

    (The method CreateChildControls : that places the whole controls in a HtmlTable)

    (The first Button_Click method, for the button that puts the data from the WebPart in the Custom list)

    (The second Button_Click method, where there is my problem, that is supposed to get the information from the custom List to the WebPart)

    This previous Button_Click has for code :

    private void button_Clic(object sender, EventArgs e)
    {
         this.EnsureChildControls();

         SPSite MySite = new SPSite(SPContext.Current.Site.Url);
         SPWeb CurrentSite = MySite.OpenWeb();

         SPList MyList = CurrentSite.Lists["TheNameOfMyList"];
         SPQuery quer = new SPQuery(MyList.DefaultView);

         // The Query (necessary to get the items of my list)

         quer.Query = "<Where><Eq><FieldRef Name = 'AField'/><ValueType='Text'>ValueOfTheField</Value</Eq></Where>";

         SPListItemCollection items = MyList.GetItems(quer);

          //What is not working : I want to put the information contained in "AField" in a textBox of my WebPart.

          foreach (SPListItem item in items)
         {
               if( (string)item["AField"] == "AText" )
               {
                    WebPartTextBox.Text = (string)item["AField"]; 
               }     
         }
    }

    I don't know if it's clearer for you...
    I don't have the time now, but I can try to write a reduction of my code later if you think it would be helpful...
    Friday, August 22, 2008 12:43 PM
  • This is a really simplified C# code of my WSS WebPart :

    using System;

    using System.Collections.Generic;

    using System.Linq;

    using System.Text;

    using System.Web;

    using System.Web.UI;

    using System.Web.UI.WebControls;

    using System.Web.UI.WebControls.WebParts;

    using System.Web.UI.HtmlControls;

    using Microsoft.SharePoint;

    using Microsoft.SharePoint.WebControls;

    using System.Drawing;

     

    namespace ClassLibrary15

    {

        public class Formular : WebPart

        {

            private Label TitleWP = new Label();

            private TextBox Field = new TextBox();

     

            private Button DataFromWebPartToCustomList = new Button();

            private Button DataFromCustomListToWebPart = new Button();

     

            HtmlTable TableHtml = new HtmlTable();

     

            protected override void CreateChildControls()

            {

                //Authentification condition (Security)

     

                if(HttpContext.Current.User.Identity.IsAuthenticated)

                {

                    //The Title

     

                    TitleWP.Text = "<b>Information Transfer WebPart </b>";

                    Field.Text = "Write something...";

     

                    HtmlTableCell TitleFieldCell = new HtmlTableCell();

                    HtmlTableRow TitleFieldRow = new HtmlTableRow();

     

                    TitleFieldCell.Controls.Add(TitleWP);

                    TitleFieldCell.Controls.Add(Field);

                    TitleFieldRow.Cells.Add(TitleFieldCell);

     

                    //The Buttons

     

                    DataFromWebPartToCustomList.Text = "Click here to transfer the text in the custom list";

                    DataFromCustomListToWebPart.Text = "Click here to retrieve the text from the list to the WebPart";

                   

                    DataFromWebPartToCustomList.Click += new EventHandler(WPCustomList_Click);

                    DataFromCustomListToWebPart.Click += new EventHandler(CustomListWP_Click);

     

                    HtmlTableCell DataButtonsCell = new HtmlTableCell();

                    HtmlTableRow DataButtonsRow = new HtmlTableRow();

     

                    DataButtonsCell.Controls.Add(DataFromWebPartToCustomList);

                    DataButtonsCell.Controls.Add(DataFromCustomListToWebPart);

                    DataButtonsRow.Cells.Add(DataButtonsCell);

     

                    //The Html Table

     

                    TableHtml.Rows.Add(TitleFieldRow);

                    TableHtml.Rows.Add(DataButtonsRow);

     

                    TableHtml.BgColor = Color.PaleTurquoise.Name;

     

                    TableHtml.CellSpacing = 15;

     

                    Controls.Add(TableHtml);

     

                }

     

            }

     

            private void WPCustomList_Click(object sender, EventArgs e)

            {

                SPSite MySite = new SPSite(SPContext.Current.Site.Url);

                SPWeb CurrentSite = MySite.OpenWeb();

     

                SPList list = CurrentSite.Lists["CustomListName"];

     

                SPListItem newListItem = list.Items.Add("", SPFileSystemObjectType.File, "NewElement");

     

                newListItem["CustomListTextField"] = Field.Text;

     

                newListItem.Update();

            }

     

            private void CustomListWP_Click(object sender, EventArgs e)

            {

                SPSite MySite = new SPSite(SPContext.Current.Site.Url);

                SPWeb CurrentSite = MySite.OpenWeb();

     

                SPList list = CurrentSite.Lists["CustomListName"];

     

                //The Query (with a 'Query" field in the WSS Custom List to retrieve all the elements)

     

                SPQuery quer = new SPQuery(list.DefaultView);

                quer.Query = "<Where><Eq><FieldRef Name = 'QueryInternalName'/><Value Type='Text'>Yes</Value></Eq></Where>";

     

                //The problematic part of the code

     

                SPListItemCollection items = list.GetItems(quer);

     

                foreach (SPListItem item in items)

                {

                    if ((string)item["CustomListTextField"] == "AText")

                    {

                        Field.Text = (string)item["CustomListTextField"];

                    }

                }

     

            }

     

        }

    }

    Of course, to make this code work, you need to create a Custom List in WSS called CustomListName with a "Query" field (with the text "Yes" for each element), and a CustomListTextField field.

    Let's just remember the scenario :

    -> I have programmed a WebPart, that is a kind of "formular", with more than 100 WebControls (Labels, TextBox, CheckBoxLists, CheckBox, Buttons).
    -> I want to use in WSS the information written by the user in my WebPart. So I've programmed a button that gets the information of the WebPart and place it in a Custom List.
    -> Now, the custom list is not easy to read for the users (too much data). Consequently, because my WebPart has a much better presentation,  I want to code another button which will do the contrary : get the information of my custom list and put it in my WebPart. This button is necessary for the visibility of these informations.


    I hope this code would help you to understand my problem and to resolve it.

    Thanks in advance...

    Monday, August 25, 2008 7:36 AM