Programatically select and bind Sharepoint list items - c#

I have some code to bind SharePoint list items to text boxes. But I only got the code to bind one item. My list contains two columns (ID and Name):
*ID Name*
1 Steven
2 Joe
3 Henry
This code picks out the Name field from the first item (that means my textbox will show "Steven":
try
{
SPQuery query = new SPQuery();
query.Query = "";
query.ViewFields = "";
query.RowLimit = 100;
using (SPSite site = new SPSite(SPContext.Current.Web.Url))
{
using (SPWeb web = site.OpenWeb())
{
SPList list = web.Lists.TryGetList("Employee List");
if (list != null)
{
if (list.GetItems(query).GetDataTable() != null)
{
DataTableReader rdr = list.GetItems(query).GetDataTable().CreateDataReader();
if (rdr.Read())
{
TextBox1.Text = rdr["Name"].ToString();
rdr.Close();
}
}
}
}
}
}
How to select the rest of them names? I was thinking about an if-statement to check if field = ID (1, 2, 3) etc. but couldn't find out anything.

Use a while loop and it should loop through all the "Name" values.
if (list.GetItems(query).GetDataTable() != null)
{
using (DataTableReader rdr = list.GetItems(query).GetDataTable().CreateDataReader())
{
while (rdr.Read())
{
TextBox1.Text = rdr["Name"].ToString();
}
}
}
Addtionally you should be using a using statement to ensure that Dispose() and Close() are both called on the DataTableReader.

Related

Accessing resources attached to list items in SharePoint

I'm accessing a list of calendar items on a SharePoint2013 site like so:
public ListItemCollection GetListByTitle(string title)
{
ClientContext context = new ClientContext(_site);
List list = context.Web.Lists.GetByTitle(title);
ListItemCollection listItems = list.GetItems(new CamlQuery()); // Empty CamlQuery to return all items in list
context.Load(listItems);
context.ExecuteQuery();
return listItems;
}
Then I'm passing that ListItemCollection to another method which will map some of the item's properties to a custom model
public List<CustomModel>GetListOfCustomModel(ListItemCollection listItems)
{
List<CustomModel> customModelList = new List<CustomModel>();
foreach(ListItem i in listItems)
{
FieldUserValue contact = (FieldUserValue)i.FieldValues["Contact"];
string s = (string)(contact.LookupValue);
string t = (string)i.FieldValues["Title"];
DateTime start = (DateTime)i.FieldValues["EventDate"];
// etc.
}
}
All of the "in-built" properties are easy to get, but I can't figure out how to access the resources the company has created and attached to these items.
E.g. each calendar item has a "Room" resource attached. I understand this is "meta data" but surely I should be able to access it somehow? It must be linked to the item I just don't know where to look. When I do a SharePoint list view for every column in the list I can see the "room" resource is generated as a link with reference to the resource.
Or am I going to end up viewing the text response from viewing my LISTALL page in a web request and parse the room out using good old fashioned string manipulation?!
I'd been looking at this for a couple of days, and I found a piece of code that translates a ListItemCollection to a DataTable
This code handled Microsoft.SharePoint.Client.FieldLookupValue, Microsoft.SharePoint.Client.FieldUserValue and Microsoft.SharePoint.Client.FieldUserValue[] but when I was looking at my Excel output I saw a Microsoft.SharePoint.Client.FieldLookupValue[]
Debugged the code again and drilled down into this instance of a FieldLookupValue[] called Facilities which, lo and behold, has the room and all other "Resources" in there.
SHORT ANSWER: Don't look for resources, look for FACILITIES
Here's some code I lifted from another answer site that cycles through ListItemCollection and transposes info to a DataTable but amended to show Id as well as value for FieldUserValue arrays and, more importantly, do the same for FieldLookupValue arrays:
public DataTable GetDataTableFromListItemCollection(ListItemCollection listItems)
{
DataTable dt = new DataTable();
foreach (var field in listItems[0].FieldValues.Keys)
{
dt.Columns.Add(field);
}
foreach (var item in listItems)
{
DataRow dr = dt.NewRow();
foreach (var obj in item.FieldValues)
{
if (obj.Value != null)
{
string key = obj.Key;
string type = obj.Value.GetType().FullName;
if (type == "Microsoft.SharePoint.Client.FieldLookupValue")
{
dr[obj.Key] = ((FieldLookupValue)obj.Value).LookupValue;
}
else if (type == "Microsoft.SharePoint.Client.FieldUserValue")
{
dr[obj.Key] = ((FieldUserValue)obj.Value).LookupValue;
}
else if (type == "Microsoft.SharePoint.Client.FieldUserValue[]")
{
FieldUserValue[] multValue = (FieldUserValue[])obj.Value;
foreach (FieldUserValue fieldUserValue in multValue)
{
dr[obj.Key] += "&" + fieldUserValue.LookupId + "=" + fieldUserValue.LookupValue;
}
}
else if (type == "Microsoft.SharePoint.Client.FieldLookupValue[]")
{
FieldLookupValue[] multValue = (FieldLookupValue[])obj.Value;
foreach (FieldLookupValue fieldLookupValue in multValue)
{
dr[obj.Key] += "&" + fieldLookupValue.LookupId + "=" + fieldLookupValue.LookupValue;
}
}
else if (type == "System.DateTime")
{
if (obj.Value.ToString().Length > 0)
{
var date = obj.Value.ToString().Split(' ');
if (date[0].Length > 0)
{
dr[obj.Key] = date[0];
}
}
}
else
{
dr[obj.Key] = obj.Value;
}
}
else
{
dr[obj.Key] = null;
}
}
dt.Rows.Add(dr);
}
return dt;
}
https://social.technet.microsoft.com/Forums/en-US/4bf89ee1-50a1-4c21-9ef9-51bd4d2ae155/convert-listitemcollection-to-datatable-without-looping-through-all-list-items-using-csom?forum=SP2016

add SPListItem to a SPListItemCollection

I have the following code for load a list from sharepoint site.
ALl is working well exept a SPList item to SPListItemCollection.
private void Data_load()
{
DataTable dt = new DataTable();
string currentName = SPContext.Current.Web.CurrentUser.Name;
SPQuery query = new SPQuery();
query.Query = "<Where><Eq><FieldRef Name='Editor'/><Value Type='Person or Group'>" + currentName + "</Value></Eq></Where>";
using (SPSite site = new SPSite("http://spdev-6/"))
{
using (SPWeb web = site.OpenWeb())
{
SPList lists = web.GetList("Lists/Advertisements");
SPListItemCollection items = lists.GetItems(query);
if (items.Count > 0)
{
DataRow dr=null;
SPListItemCollection ITEM = null;
foreach(SPListItem item in items)
{
string A = item["Approval Status"].ToString();
if(A== "2")
{
ITEM.Add(item);
}
}
if(dt.Rows.Count==0)
lbldata.Text = "No data to show";
// dt = items.GetDataTable();
}
else
lbldata.Text = "No data to show";
GridViewD.DataSource = dt;
GridViewD.DataBind();
HttpContext.Current.Session["Advertisement"] = dt;
}
}
}
Now in if(A== "2"){ ITEM.Add(item); }
I want to add SPListItem to a SPListItemCollection. Please help.
You are trying to add an item into null because your ITEM is null. I don't know what error you are getting ( your don't write it) but you must initialize your collection:
if (items.Count > 0)
{
DataRow dr=null;
SPListItemCollection ITEM = ... //
foreach(SPListItem item in items)
{
string A = item["Approval Status"].ToString();
if(A== "2")
{
SPListItem myItem = ITEM.Add();
// set your item's fields here
// Use indexers on this object for each field to assign specific values, and then call the Update method on the item to effect changes in the database.
myItem["Approval Status"] = item["Approval Status"];
...
myItem.Update();
}
}
if(dt.Rows.Count==0)
lbldata.Text = "No data to show";
// dt = items.GetDataTable();
}

Dynamically creating a CheckBoxList

I am trying to create a dynamic menu with a title and group of checkboxes. So the output would be something like this: (pseudocode-ly)
Title 1
-checkbox1 -checkbox2 -checkbox3
Title 2
-checkbox1 -checkbox2 -checkbox3
I can get the Title back just fine, but my checkboxes are not. (See below)
Care
System.Web.UI.WebControls.CheckBoxList
Corporate & Enterprise Solutions
System.Web.UI.WebControls.CheckBoxList
I realize I am returning a DataSet, I just don't know how to handle it.
BusinessUnit bu = new BusinessUnit();
DataSet businessNames = bu.ListBusinessUnitNames();
ArrayList buNames = new ArrayList();
if (businessNames.Tables.Count > 0 && businessNames.Tables[0].Rows.Count > 0)
{
foreach (DataRow row in businessNames.Tables[0].Rows)
{
buNames.Add(row["BSUN_NAME"].ToString());
}
}
int counter = 1;
foreach (string name in buNames)
{
Label lblName = new Label();
lblName.ID = "unitName_" + counter;
lblName.Text = name;
CheckBoxList chkBoxes = new CheckBoxList();
chkBoxes.ID = name + "Programs_" + counter;
foreach (string item in buNames)
{
DataSet buPrograms = bu.ListBusinessUnitPrograms(item);
foreach (DataRow row in buPrograms.Tables[0].Rows)
{
chkBoxes.DataTextField = row[0].ToString();
chkBoxes.Text = chkBoxes.DataTextField;
}
}
programs.InnerHtml += lblName.Text + chkBoxes;
counter++;
}
Here are the mechanics for doing it in code:
ListItem LI1 = new ListItem("aaa");
ListItem LI2 = new ListItem("bbb");
LI1.Selected = true;
LI2.Selected = false;
chkBoxes.Items.Add(LI1);
chkBoxes.Items.Add(LI2);
(Assuming you're using WebForms [aspx])
In your code example, the statement programs.InnerHtml += lblName.Text + chkBoxes; is appending the value of the default .ToString() implementation of the chkBoxes object. To actually add the checkboxes to the page, you will need some sort of container control (such as a Placeholder) on the page, and append your dynamically created control to the container's Controls collection via phPlaceholder.Controls.Add(chkBoxes)

How to use iTextSharp to populate radio button

I have a table and one of the column is YesNo which is of type varchar(3). I have two radio buttons in my PDF file which is in an array:
pg1rb (radio group field)
--> c1 (radio button one (yes))
--> c2 (radio button two (no))
I set textboxes like this in my code:
formFieldMap["topmostSubform[0].Page1[0].f1_01_0_[0]"] = reader.GetValue(0).ToString();
How can I select YES or NO radio button based on the row value?
Can I do something like this:
formFieldMap["pg1rb"] = reader.GetBoolean(10); //10 is the 9th column which is Yes/No value
Or do I get the value and based on it select the radio button, something like this:
if (reader.GetValue(10).ToString() == "Yes") {
formFieldMap["pg1rb"][c1] = "1";
else {
formFieldMap["pg1rb"][c2] = "1";
}
My SQL table:
I am trying to follow this site: Website example
My function that actually does the conversion:
public void writeData(string k, string c)
{
Conn = new SqlConnection(cString);
Conn.Open();
//MessageBox.Show(k);
//MessageBox.Show(c);
var pdfPath = Path.Combine(Server.MapPath("~/PDFTemplates/forme.pdf"));
// Get the form fields for this PDF and fill them in!
var formFieldMap = PDFHelper.GetFormFieldNames(pdfPath);
//if more than multiple entries, verify by name and the last four ssn
sqlCode = "SELECT * FROM [DSPCONTENT01].[dbo].[TablePDFTest] WHERE [name] = '" + k + "' AND [ssn3] = " + c + "";
//sqlCode = "SELECT * FROM [DSPCONTENT01].[dbo].[TablePDFTest] WHERE [name] = #name2 AND [ssn3] = #ssnnum";
//MessageBox.Show("" + sqlCode.ToString());
using (SqlCommand command = new SqlCommand(sqlCode, Conn))
{
command.CommandType = CommandType.Text;
//command.Parameters.AddWithValue("name2", k);
//command.Parameters.AddWithValue("ssnnum", c);
using (reader = command.ExecuteReader())
{
if (reader.HasRows)
{
if (reader.Read())
{
//MessageBox.Show(reader.GetValue(0).ToString());
/*formFieldMap["topmostSubform[0].Page1[0].f1_01_0_[0]"] = reader.GetValue(0).ToString();
formFieldMap["topmostSubform[0].Page1[0].f1_02_0_[0]"] = reader.GetValue(1).ToString();
formFieldMap["topmostSubform[0].Page1[0].f1_04_0_[0]"] = reader.GetValue(2).ToString();
formFieldMap["topmostSubform[0].Page1[0].f1_05_0_[0]"] = reader.GetValue(3).ToString();
formFieldMap["topmostSubform[0].Page1[0].f1_07_0_[0]"] = reader.GetValue(4).ToString();
formFieldMap["topmostSubform[0].Page1[0].social[0].TextField1[0]"] = reader.GetValue(5).ToString();
formFieldMap["topmostSubform[0].Page1[0].social[0].TextField2[0]"] = reader.GetValue(6).ToString();
formFieldMap["topmostSubform[0].Page1[0].social[0].TextField2[1]"] = reader.GetValue(7).ToString();
formFieldMap["topmostSubform[0].Page1[0].social[0].TextField2[2]"] = reader.GetValue(8).ToString();
formFieldMap["topmostSubform[0].Page1[0].social[0].TextField2[3]"] = reader.GetValue(9).ToString();*/
if (reader.GetValue(10).ToString() == "Yes")
{
//MessageBox.Show("YES");
}
else if (reader.GetValue(10).ToString() == "No")
{
//MessageBox.Show("NO");
}
}
}
}
}
// Requester's name and address (hard-coded)
formFieldMap["topmostSubform[0].Page1[0].f1_06_0_[0]"] = "Medical Group\n12 Westchester Ave\nPurchase, NY 10121";
var pdfContents = PDFHelper.GeneratePDF(pdfPath, formFieldMap);
PDFHelper.ReturnPDF(pdfContents, "Completed-W9.pdf");
}
The PDFHelper class:
using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Web;
using System.IO;
using iTextSharp.text.pdf;
public class PDFHelper
{
public static Dictionary<string, string> GetFormFieldNames(string pdfPath)
{
var fields = new Dictionary<string, string>();
var reader = new PdfReader(pdfPath);
foreach (DictionaryEntry entry in reader.AcroFields.Fields)
fields.Add(entry.Key.ToString(), string.Empty);
reader.Close();
return fields;
}
public static byte[] GeneratePDF(string pdfPath, Dictionary<string, string> formFieldMap)
{
var output = new MemoryStream();
var reader = new PdfReader(pdfPath);
var stamper = new PdfStamper(reader, output);
var formFields = stamper.AcroFields;
foreach (var fieldName in formFieldMap.Keys)
formFields.SetField(fieldName, formFieldMap[fieldName]);
stamper.FormFlattening = false;
stamper.Close();
reader.Close();
return output.ToArray();
}
// See http://stackoverflow.com/questions/4491156/get-the-export-value-of-a-checkbox-using-itextsharp/
public static string GetExportValue(AcroFields.Item item)
{
var valueDict = item.GetValue(0);
var appearanceDict = valueDict.GetAsDict(PdfName.AP);
if (appearanceDict != null)
{
var normalAppearances = appearanceDict.GetAsDict(PdfName.N);
// /D is for the "down" appearances.
// if there are normal appearances, one key will be "Off", and the other
// will be the export value... there should only be two.
if (normalAppearances != null)
{
foreach (var curKey in normalAppearances.Keys)
if (!PdfName.OFF.Equals(curKey))
return curKey.ToString().Substring(1); // string will have a leading '/' character, so remove it!
}
}
// if that doesn't work, there might be an /AS key, whose value is a name with
// the export value, again with a leading '/', so remove it!
var curVal = valueDict.GetAsName(PdfName.AS);
if (curVal != null)
return curVal.ToString().Substring(1);
else
return string.Empty;
}
public static void ReturnPDF(byte[] contents)
{
ReturnPDF(contents, null);
}
public static void ReturnPDF(byte[] contents, string attachmentFilename)
{
var response = HttpContext.Current.Response;
if (!string.IsNullOrEmpty(attachmentFilename))
response.AddHeader("Content-Disposition", "attachment; filename=" + attachmentFilename);
response.ContentType = "application/pdf";
response.BinaryWrite(contents);
response.End();
}
}
Your question was confusing because it used a reader object that didn't refer to iTextSharp's PdfReader class and it used a formFieldMap object of which the type was unknown (it doesn't seem related to iTextSharp). Your edit was very welcome to understand the question.
The field names you mention look as if they are fields in an XFA form, but the article you refer to talks about filling out AcroForm documents, so let's assume that your form was indeed born as an XFA form, but later on converted to an AcroForm.
In this case, nobody will be able to tell you which values to pick to set the radio buttons without seeing the PDF. Please download chapter 6 of my book and read section 6.3.5, more specifically where it says Inspecting the form and its fields. On page 183, you can read that the possible values for a group of radio buttons is either "Off"–no radio button is selected— or a code that is defined in the form itself.
For instance: in the example from the book, the possible values for the category group were spec, toro, anim, etc...
This means that you can set a radio box in that group like this:
formFields.SetField("category", "spec");
or:
formFields..SetField("category", "toro");
or:
formFields.SetField("category", "anim");
and so on.
So, if you want to set a radio button in a radiogroup named pg1rb, you first need to know which are the possible values. You assume that the possible values are "Yes" and "No" in which case you could use:
formFields.SetField("pg1rb", "Yes");
or
formFields.SetField("pg1rb", "No");
But the possible values could also be "1" and "0", "On" and "Off", "true" and "false",... The possible values were chosen by the person who created the form.
You can get these values programmatically by using the code from page 182:
StringBuilder sb = new StringBuilder();
sb.Append("Possible values for pg1rb:");
sb.Append(Environment.NewLine);
states = form.GetAppearanceStates("pg1rb");
for (int i = 0; i < states.Length - 1; i++) {
sb.Append(states[i]);
sb.Append(", ");
}
sb.Append(states[states.Length - 1]);
Inspect what was written to the sb object and you have the values you are looking for.

How to add a number of records into a List<T>

I have created an asp.net application using Entity Framework. In this I want to add the records into a list. For this I have to use the foreach loop but it always adding only last record data for all records, meaning it's showing same data. Here I have pasted my code. Please verify it once and guide where I can change.
public List<CategoryItems> ListMenuCategory(int MenuId)
{
string str = string.Empty;
string strJSON = string.Empty;
List<CategoryItems> resultmenu;
resultmenu = new List<CategoryItems>();
List<CategoryItems> Result;
Result = new List<CategoryItems>();
bool check = true;
var objmenuCategory = from cat in objEntity.menucategories where cat.MenuId == MenuId && cat.Active == check select cat;
CategoryItems Categorylist = new CategoryItems();
foreach (menucategory category in objmenuCategory)
{
Categorylist.CategoryName = category.CategoryName;
Categorylist.Description = category.Description;
int menuid = category.MenuCategoryId;
List<menuitem> menuitems = GetMenucategories(menuid);
foreach (var items in menuitems)
{
Categorylist.ItemName = items.ItemName;
Categorylist.Description = items.Description;
Categorylist.Price = (float)items.Price;
string Image = items.Picture;
Categorylist.Picture = "http://restaurantmanager.testshell.net/Images/" + Image;
Categorylist.Thumbnail = "http://restaurantmanager.testshell.net/Images/" + items.Thumbnail;
if (items.CreatedDate != null)
{
Categorylist.CreatedDate = (DateTime)items.CreatedDate;
}
if (items.ModifiedDate != null)
{
Categorylist.ModifiedDate = (DateTime)items.ModifiedDate;
}
Result.Add(Categorylist);
}
// Result.AddRange(menus);
}
return Result;
}
private List<menuitem> GetMenucategories(int p)
{
restaurantEntities objEntity1 = new restaurantEntities();
var menuitems = from items in objEntity1.menuitems where items.MenuCategoryId == p select items;
return menuitems.ToList();
}
You are creating the Categorylist item outside of the loops, so you are only using one single item, filling it with different data and adding it over and over to the result.
You have to create the item inside the innermost loop, so that each iteration gets its own object.
Note: ChrisF also spotted that you call AddRange inside the loop, which has the result that you will add the same set of items over and over. You don't need to call AddRange at all, you can just skip the Result list entirely and just return resultmenu instead.

Categories