Add values to a list contains a Lookup Field - sharepoint

I have a list named "Designation" that contains a Designation Code and Designation Name.
I have another list named "Employee" that contains Employee Name and Designation Name (as a Lookup Field).
I am able to insert values to "Employee" list using the following code.
protected void AddEmp(object sender, EventArgs e)
{
string emp_name = txtEmployeeName.Text;
string emp_designation = ddlDesignation.SelectedValue;
using (SPSite site = new SPSite("My Site"))
{
using (SPWeb web = site.OpenWeb())
{
SPSecurity.RunWithElevatedPrivileges(delegate()
{
web.AllowUnsafeUpdates = true;
SPList splist_employees = web.Lists["Employee"];
SPList splist_designations = web.Lists["Designations"];
SPListItemCollection splc_items = splist_employees.Items;
SPListItem spli_item = splc_items.Add();
SPFieldLookup lookup = splist_employees.Fields["Designated"] as SPFieldLookup;
string fieldName = lookup.LookupField;
spli_item["Employee Name"] = emp_name;
spli_item[fieldName] = GetLookFieldIDS(emp_designation, splist_designations);
spli_item.Update();
});
}
}
}
public static string GetLookFieldIDS(string lookupValues, SPList lookupSourceList)
{
string id = string.Empty;
SPFieldLookupValueCollection lookupIds = new SPFieldLookupValueCollection();
SPQuery query = new Microsoft.SharePoint.SPQuery();
query.Query = "<Where><Eq><FieldRef Name='Designation' /><Value type='Text'>"+lookupValues + "</Value></Eq></Where>";
SPListItemCollection listItems = lookupSourceList.GetItems(query);
foreach (Microsoft.SharePoint.SPListItem item in listItems)
{
id = item.ID.ToString();
}
return id;
}
Here I have given the field name as 'Designation' inside the query.
But, I want to find the field name based on the value given from the user end instead of hard-coding the field name as 'Designation'.
Any help is greatly appreciated. Thanks in advance.

Not sure about your request but, you could pass SPFieldLookup.LookupField property to your GetLookFieldIDS method and use that variable instead of "Designation"
spli_item[fieldName] = GetLookFieldIDS(emp_designation, splist_designations, lookup.LookupField);

Related

Update/Change custom TaxonomyFieldValue in document library list in sharepoint using C# CSOM

list of documents thats contains custom taxonomy field column named subject.
Need to update subject of thousands records/documents.
Please any idea to update the taxonomy field such subject programtically using C# CSOM
Please try to use this method:
public void UpdateTaxonomyField(ClientContext ctx, List list,ListItem listItem,string fieldName,string fieldValue)
{
Field field = list.Fields.GetByInternalNameOrTitle(fieldName);
TaxonomyField txField = clientContext.CastTo<TaxonomyField>(field);
TaxonomyFieldValue termValue = new TaxonomyFieldValue();
string[] term = fieldValue.Split('|');
termValue.Label = term[0];
termValue.TermGuid = term[1];
termValue.WssId = -1;
txField.SetFieldValueByValue(listItem, termValue);
listItem.Update();
ctx.Load(listItem);
ctx.ExecuteQuery();
}
public static void UpdateListofLibraryHavingTaxonomyField()
{
string siteUrl = "http://abc:55555/sites/xyz/";
string libName = "Knowledge Repos";
string strTermGuid = "Your new/update term guid";
try
{
Dictionary<string, string> dictIdsSubjectsChange = ReadFromExcel();//Here to read all records (approx 2000 records) that we want to change
ClientContext clientContext = new ClientContext(siteUrl);
List list = clientContext.Web.Lists.GetByTitle(libName);
FieldCollection fields = list.Fields;
Field field = fields.GetByInternalNameOrTitle("Subject1");
ListItemCollection listItems = list.GetItems(CamlQuery.CreateAllItemsQuery());
clientContext.Load(listItems, items => items.Include(i => i["Subject1"], i => i["ID"]));
clientContext.Load(fields);
clientContext.Load(field);
clientContext.ExecuteQuery();
TaxonomyField txField = clientContext.CastTo<TaxonomyField>(field);
TaxonomyFieldValue termValue = null;
if (dictIdsSubjectsChange != null)
{
foreach (ListItem listItem in listItems)//Loop through all items of the document library
{
string strCurrentID = "0";
try
{
strCurrentID = listItem["ID"].ToString();
}
catch (Exception) { }
if (dictIdsSubjectsChange.ContainsKey(strCurrentID))//Checking to change ot not
{
termValue = new TaxonomyFieldValue();
termValue.Label = "Special Knowledge";
termValue.TermGuid = strTermGuid;
termValue.WssId = 246;
txField.SetFieldValueByValue(listItem, termValue);
listItem.Update();
clientContext.Load(listItem);
}
}
clientContext.ExecuteQuery();
}
}
catch (Exception ex) { }
}
}

SPQuery search doesn't work with "BeginsWith"

So, my problem is that my knowledge of CAML and Sharepoint is very poor.
Question: I need SPQuery for building query search, search text I have from textbox. I expect that my query returns me item(s) (for example, I type in textbox "Jo" and query returns me all items with surname "Johnson", or name "John", etc)
1)TextChanged works ok. I've check it, there is ok
2) SPGridView views items ok. Items from SPList I add to gridView - there are viewd by gridview.
3) But my query doesn't work. Please, help with links/advises
public class VisualWebPart1 : WebPart
{
SPSite site;
SPWeb web;
SPGridView gridView;
SPDataSource dataSource;
TextBox searchTextBox;
UpdatePanel panel;
SPList list;
SPList resultList;
string currentList;
// Visual Studio might automatically update this path when you change the Visual Web Part project item.
private const string _ascxPath = #"~/_CONTROLTEMPLATES/CRMSearchWebPart/VisualWebPart1/VisualWebPart1UserControl.ascx";
protected override void CreateChildControls()
{
gridView = new SPGridView();
searchTextBox = new TextBox();
panel = new UpdatePanel();
searchTextBox.AutoPostBack = true;
searchTextBox.Visible = true;
searchTextBox.Enabled = true;
searchTextBox.TextChanged += new EventHandler(searchTextBox_TextChanged);
gridView.Visible = true;
gridView.Enabled = true;
gridView.AutoGenerateColumns = false;
AddColumnToSPGridView("Surname", "Surname");
panel.UpdateMode = UpdatePanelUpdateMode.Conditional;
panel.ContentTemplateContainer.Controls.Add(searchTextBox);
panel.ContentTemplateContainer.Controls.Add(gridView);
Control control = Page.LoadControl(_ascxPath);
Controls.Add(control);
Controls.Add(panel);
}
protected override void Render(HtmlTextWriter writer)
{
panel.RenderControl(writer);
}
//Open WebSite with List "listName"
private void OpenWebSite(string listName)
{
site = SPContext.Current.Site;
web = site.OpenWeb();
list = web.Lists[listName];
}
//Add Column to gridView
private void AddColumnToSPGridView(string HeaderText, string Datafield)
{
SPBoundField boundField = new SPBoundField();
boundField.HeaderText = HeaderText;
boundField.DataField = Datafield;
gridView.Columns.Add(boundField);
}
//Build query for search; fieldName - Name of column of current List, searchQuery - our query
private string BuildQuery(string fieldRefName, string searchQuery)
{
string query = "";
switch (fieldRefName)
{
case "Surname":
query = "<Where><BeginsWith><FieldRef Name='Surname'/>" +
"<Value Type=Text>"+searchQuery+"</Value></BeginsWith></Where>";
break;
case "Name":
query = query = "<Where><BeginsWith><FieldRef Name='Name'/>" +
"<Value Type=Text>"+searchQuery+"</Value></BeginsWith></Where>";
break;
case "PassportNumber":
query = "<Where><BeginsWith><FieldRef Name='PassportNumber'/>" +
"<Value Type=Text>"+searchQuery+"</Value></BeginsWith></Where>";
break;
default: break;
}
return query;
}
// search in List for selected items and returns SPGridView
private void searchTextBox_TextChanged(object sender, EventArgs e)
{
dataSource = new SPDataSource();
string querySearch = searchTextBox.Text;
OpenWebSite("Surnames");
string query = BuildQuery("Surname", querySearch);
SPQuery spQuery = new SPQuery();
spQuery.ViewFields = "<FieldRef Name = 'Title'/><FieldRef Name = 'Surname'/><FieldRef Name = 'Name'/>";
spQuery.Query = query;
SPListItemCollection items = list.GetItems(query);
foreach (SPListItem item in items)
{
searchTextBox.Text += item["Surname"] + " ";
}
//resultList = web.Lists["TempSurnames"];
//resultList = AddItemsToSPList(resultList, items);
BindDataSource(dataSource, resultList);
//resultList = AddSPList("Result2", "Result list");
//resultList = AddItemsToSPList(resultList, items);
list = AddItemsToSPList(list, items);
//BindDataSource(dataSource, resultList);
BindDataSource(dataSource, list);
BindGridView(gridView, dataSource);
//var item = list.Items[3];
//var item = resultList.Items[1];
//searchTextBox.Text = item["Surname"].ToString();
//resultList.Delete();
}
//Binds datasource of existing gridView with SPDataSource
private void BindGridView(SPGridView gridview, SPDataSource datasource)
{
gridview.DataSource = datasource;
gridview.DataBind();
}
//Add SPListItem items to SPList
private SPList AddItemsToSPList(SPList spList, SPListItemCollection collection)
{
foreach (SPListItem item in collection)
{
var listItem = spList.AddItem();
listItem = item;
}
return spList;
}
//Binds existing SPDataSource to SPList
private void BindDataSource(SPDataSource spDataSource, SPList spList)
{
spDataSource.List = spList;
}
private SPList AddSPList(string listName, string listDescription)
{
OpenWebSite("Surnames");
SPListCollection collection = web.Lists;
collection.Add(listName, listDescription, SPListTemplateType.CustomGrid);
resultList = web.Lists[listName];
return resultList;
}
Update:
This part gives me an error:
SPListItemCollection items = list.GetItems(query);
foreach (SPListItem item in items)
{
searchTextBox.Text += item["Surname"] + " ";
}
System.ArgumentException: Value does not fall within the expected
range
You have to include the field Surname into the view fields of the query:
SPQuery query = // ...
query.ViewFields = "<FieldRef Name='Surname' />";
// ...
You can understand the view fields like the SELECT part of a SQL query.
Have you debugged your code to check the query string that is generated? Also, you have query = query = under the Name switch.
Also, you know that the switch is case sensitive, so ensure you enter your searchQuery option appropriately.

How to add multiple lookup value in sharepoint List.While adding item in sharepoint

My Task have multiple relateddocId for example RelatedDoc="3,5,2,6", now i need to add multiplevalue to the sharepoint lookup fields called related Document which is in task list. how to add this?
For ref see my code below
private static void CreateItem(SPWeb web, SPList TaskList, string FolderURL, string ItemName, string RelatedDoc)
{
var ParentURL = string.Empty;
if (!TaskList.ParentWebUrl.Equals("/"))
{
ParentURL = TaskList.ParentWebUrl;
}
SPListItem _taskList = TaskList.AddItem(ParentURL + FolderURL, SPFileSystemObjectType.File, null);
_taskList["Title"] = ItemName;
string DocName = "4,6,3,6";//Document ref id.
SPFieldLookupValue lookupvalue = new SPFieldLookupValue();
if (DocName != "")
lookupvalue = new SPFieldLookupValue(RelatedDoc, DocName);
_taskList["EYRelatedSharedDocument"] = lookupvalue;
_taskList.Update();
}
SPFieldLookupValueCollection documents = new SPFieldLookupValueCollection();
foreach ( ... )
{
documents.Add(new SPFieldLookupValue(documentId, documentTitle));
}
_taskList["EYRelatedSharedDocument"] = documents;
_taskList.Update();

SharePoint 2010: Count ListItem Attachments using Client Object Model

Does anyone know how to read the number of attachments, and the names etc for a ListItem using the Client .Net Object model in SharePoint?
Thanks
// For getting the list item field information
public void LoadPropertyInfo()
{
using (context = new ClientContext(siteCollectionUrl))
{
spWeb = context.Web;
propertiesList = spWeb.Lists.GetByTitle(listName);
FieldCollection fields = propertiesList.Fields;
context.Load(fields);
SP.CamlQuery query = new SP.CamlQuery();
query.ViewXml = string.Format("<View><Query><Where><Eq><FieldRef Name=\"{0}\" /><Value Type=\"Text\">{1}</Value></Eq></Where></Query></View>", propertyID, PropertyIDValue);
listItems = propertiesList.GetItems(query);
context.Load(listItems);
context.ExecuteQueryAsync(GetRequestSucceeded, RequestFailed);
}
}
// Pass the item id here for getting the attachments
private void GetAttchmentCollection(string id)
{
string RedirectHost = string.Empty;
string Host = string.Empty;
context = SP.ClientContext.Current;
RedirectHost = serviceUrl + "_vti_bin/Lists.asmx";
BasicHttpBinding binding = new BasicHttpBinding();
if (System.Windows.Browser.HtmlPage.Document.DocumentUri.Scheme.StartsWith("https"))
{
binding.Security.Mode = BasicHttpSecurityMode.Transport;
}
binding.MaxReceivedMessageSize = int.MaxValue;
EndpointAddress endpoint = new EndpointAddress(RedirectHost);
ServiceReference1.ListsSoapClient oClient = new ServiceReference1.ListsSoapClient(binding, endpoint);
oClient.GetAttachmentCollectionCompleted += new EventHandler<ServiceReference1.GetAttachmentCollectionCompletedEventArgs>(oClient_GetAttachmentCollectionCompleted);
oClient.GetAttachmentCollectionAsync(listName, id);
}
Your can try this link too.
http://helpmetocode.blogspot.com/2011/11/managed-client-object-models-in.html

How to read a Choice Field from Sharepoint 2010 Client Object Model

I'm using Sharepoint 2010 Object Model. I'm trying to retrive the content of a Custom List. Everything works fine except if when I try to retrieve a Choice Field.
When I try to retrieve the choice field, I got an PropertyOrFieldNotInitializedException exception...
Here is the code I'm using:
ClientContext clientContext = new ClientContext("https://mysite");
clientContext.FormsAuthenticationLoginInfo = new FormsAuthenticationLoginInfo("aaa", bbb");
clientContext.AuthenticationMode = ClientAuthenticationMode.FormsAuthentication;
List list = clientContext.Web.Lists.GetByTitle("mylist");
CamlQuery camlQuery = new CamlQuery();
camlQuery.ViewXml = "<View/>";
ListItemCollection listItems = list.GetItems(camlQuery);
clientContext.Load(listItems);
clientContext.ExecuteQuery();
foreach (ListItem listItem in listItems)
{
listBoxControl1.Items.Add(listItem["Assigned_x0020_Company"]);
}
var list = clientContext.Web.Lists.GetByTitle(listName);
clientContext.ExecuteQuery();
clientContext.Load(list.Fields, fields => fields.Include(field => field.Title));
clientContext.ExecuteQuery();
foreach (var field in list.Fields)
{
if (field.Title == "YourChoiceFieldName")
{
clientContext.Load(field);
clientContext.ExecuteQuery();
return ((FieldChoice) field).Choices;
}
}
When you read a ChoiceField in code , It will return a string array of selected choices. For example if you entered in the choice box of the column when you create it : "Company 1" ,"Company 2","Company 3 " , if user select option 1 & 2 , then returned array in code will contain "Company 1" and "Company 2" .You must change the code to the below :
foreach (ListItem listItem in listItems)
{
string[] values = (string[])listItem["Assigned_x0020_Company"];
foreach(string s in values)
{
listBoxControl1.Items.Add(s);
}
}

Resources