tags:

views:

146

answers:

2

I have a sharepoint list,

and want to get all the items of that list and and loop through each field of each item to output someting like:

"fieldname: value"

how can i do it?

thanks

A: 
    SPList list = GetList();

    foreach(SPListItem item in list.Items)
    {
      foreach (SPField field in item.Fields)
      {

        Console.WriteLine("Name : {0} - Value: {1}", 
                          field.InternalName, item[field.Id].ToString());
      }
    }

something like that??

EDIT: Fixed my code error after Kirk mentioning it.

Johan Leino
+2  A: 

Johan was close, but didn't have the actual value. The following should do:

using (SPSite site = new SPSite("<site_url_where_list_is>"))
{
    using (SPWeb web = site.OpenWeb())
    {
        SPList list = web.Lists["<list_name>"];
        foreach (SPListItem listItem in list.Items)
        {
            foreach (SPField field in list.Fields)
            {
                object value = listItem[field.Id];
                System.Diagnostics.Debug.WriteLine(field.Title + ": " + (value == null ? "(null)" : value.ToString()));
            }
        }
    }
}
Kirk Liemohn
Note that you would normally not call SPList.Items unless you want to iterate over all the records. Instead you would use SPList.GetItems(SPQuery).
Kirk Liemohn
Great of you to mention that we shouldn´t use SPList.Items but instead SPList.GetItems Kirk...that is way important on big collections...I know from experience. +1
Johan Leino