Adding an option to choicebox in SharePoint, c# - c#

I want to add an option to choicebox named 'yyy' in all lists called 'xxx'. My code prints chosen option from choicebox for every list (I guess so).
I was trying to do field.GetFieldValueAsText(???) on my 'yyy' field (in other words my choicebox) but I don't know what should I pass as an argument to that method.
Anyone has any idea how to solve this out?
Thanks in advance.
SPSite mainSite = new SPSite(path);
SPWebCollection webColl = mainSite.AllWebs;
foreach (SPWeb web in webColl)
{
SPListCollection listColl = web.Lists;
foreach (SPList list in listColl)
{
if (list.Title.Equals("xxx", StringComparison.CurrentCultureIgnoreCase))
{
SPFieldCollection fields = list.Fields;
foreach (SPField field in fields)
{
if (field.Title.Equals("yyy", StringComparison.CurrentCultureIgnoreCase))
{
foreach (SPItem item in items)
Console.WriteLine(item["yyy"]);
}
}
}
}
}

Related

C# - Remove items from List when button is clicked

My problem is; When click a button I input items in List, next in DropDownList. Problem is where i click button again exist items again into my DropDown.
How to solve this problem(sorry for image)?
List<string> companyList = new List<string>();
foreach (string item in companyList.ToList())
{
companyList.Remove(item); ----> this not working.......
}
foreach (SPListItem item in myItemCol)
{
companyList.Add(item["Company"].ToString());
}
companyList.Sort();
foreach (string item in companyList.Distinct())
{
ddComFilter.Items.Add(item.ToString());
}
You can use the Contains method to check if it is already there
if(!ddComFilter.Items.Contains(items.ToString())
{
ddComFilter.Items.Add(item.ToString());
}
This will only add the item if it is not already in the dropdown
You could check for existence of the item before add it to the list.
foreach (SPListItem item in myItemCol)
{
if(!companyList.Contains(item["Company"].ToString())
{
companyList.Add(item["Company"].ToString());
}
}
Then you need to clear the ddComFilter before adding the values to it:
companyList.Sort();
ddComFilter.Items.Clear();
foreach (string item in companyList.Distinct())
{
ddComFilter.Items.Add(item.ToString());
}
Alternate solution:
You can bind the ddComFilter using the generated list, instead for iterating the collection and add one-by-one. if so you need not to clear the collection, remove items etc. The code for this will be:
ddComFilter.Datasource = companyList;
ddComFilter.DataBind();
Here is an useful article for you
You should clear your dropdown before adding list as items:
companyList.Sort();
ddComFilter.Items.Clear(); // clear
foreach (string item in companyList.Distinct())
{
ddComFilter.Items.Add(item.ToString());
}

C# Add server users to List<>

I have created an application that checks how many users are logged into a machine and performs a count. I have used Cassia to get the usernames, however I would like to put those usernames in a list and send to my database.
I am having a problem with putting those usernames into the list.
Here is my code:
static void Main(string[] args)
{
while (!Console.KeyAvailable)
{
List<string> list = new List<string>();
string host = Dns.GetHostName();
ITerminalServicesManager manager = new TerminalServicesManager();
using (ITerminalServer server = manager.GetRemoteServer(host))
{
server.Open();
foreach (ITerminalServicesSession session in server.GetSessions())
{
NTAccount account = session.UserAccount;
if (account != null)
{
list.Add(account.ToString());
Console.WriteLine(list);
Console.WriteLine("Count: " + list.Count);
Thread.Sleep(10000);
}
}
}
}
}
When I run the application, the count is performed correctly, but the list is not displayed in my application. System.Collection.Generic.List``1[System.String] is displayed instead of the list.
Is there a way to place those usernames in a list? Or maybe an array would be better? Any suggestions?
Thank you.
Try printing out your list using following
list.ForEach(Console.WriteLine);
That will print all the list elements. One per line.
I see couple of issues here.
First one: place list creation and printing outisde your loop, otherwise you're creating new list for each session object and I really doubt it was intended.
Second one: you can't print the list using one WirteLine since in this cast it tries to use .ToString() method of list inherited from object and gives you result like System.Collection.Generic.List``1[System.String].
Instead you have to use another loop to traverse the list and print it:
List<string> list = new List<string>();
foreach (ITerminalServicesSession session in server.GetSessions())
{
NTAccount account = session.UserAccount;
if (account != null)
{
list.Add(account.ToString());
}
}
foreach (var item in list)
Console.WriteLine(item);
Console.WriteLine("Count: " + list.Count);
Thread.Sleep(10000);
This line is printing the value of list.ToString() to the console:
Console.WriteLine(list);
Your accounts are in there, but the default behavior of ToString will print information about the object's type. Try replacing that line with:
Console.WriteLine(account.ToString());
You can use this code block:
foreach (var item in list)
Console.WriteLine(item);
Console.WriteLine(list) is the same Console.WriteLine(list.ToString()).
ToString() method returns system name of the List object.

Update multiple fields in SharePoint programmatically

I'm trying to update some properties on multiple fields (with the same name) in SharePoint.
I've tried this:
var site = this.Site.RootWeb;
var fields = site.Fields;
foreach (SPField field in fields)
{
if (field.Group.Contains("My Custom Columns"))
{
if (field.Title.Contains("Custom field"))
{
if (field.DefaultValue != null) {
field.DefaultValue = null;
field.Update(true);
}
}
}
}
It updates the first column with the name "Custom field", but after it's giving me this error:
Collection was modified; enumeration operation may not execute.
at Microsoft.SharePoint.SPBaseCollection.SPEnumerator.System.Collections.IEnumerator.MoveNext()
Is it not possible to Update the object in a foreach loop?
This error occurs since you are trying to modify a field collection while iterating it.
The solution would be to replace the line:
foreach (SPField field in fields)
with
foreach (var field in fields.Cast<SPField>().ToList())
The problem I believe is with your
foreach (SPField field in fields)
line of code. You are essentially modifying the collection that you are looping over.
What I would suggest you try is looping and getting the ID's of all the fields in to a
List<GUID>
Then do a foreach statement on this collection getting each field and updating it's value.
List<Guid> guidsList = new List<guid>();
foreach (SPField field in fields)
{
if (field.Group.Contains("My Custom Columns"))
{
if (field.Title.Contains("Custom field"))
{
guidsList.add(field.id)
}
}
}
foreach(Guid currentFieldId in guidsList){
//Get your field
//Update what needs to be updated
}
Many Thanks
Truez

Foreach loop correctly

I have a data table and i'm trying to loop through the rows and create a zipCode array. This issue that i'm only getting one number 4 times. I know I'm doin something wrong but can somebody point this out to me and give and explanation.
Thanks
public string bindMap()
{
using (dal.Sys.RegionTableAdapters.region_countyListTa ta = new Cea.WebApp.JobsEq.Dal.Sys.RegionTableAdapters.region_countyListTa())
{
List<string> code = new List<string>();
dal.Sys.Region.region_countyListDataTable dt = ta.GetData(region.RegionType, region.RegionCode);
foreach (var row in dt)
{
code.Add(region.ZipCode);
}//end foreach loop
string codes = string.Join(",", code.ToArray());
return codes.ToString();
}//end for each loop
}//end bind map
You aren't using the variable that you are iterating with.
foreach (var row in dt)
{
//Not sure how you will get ZipCode from the ROW, but you get the idea.
code.Add(row["ZipCode"]);
}//end foreach loop
As a general desc of the row/cell value, I use this general (NOTE: GENERAL) block:
foreach(var item : items) {
//before adding there is maybe some casting or other work...
listName.add(item["FieldName"]);
}
Understandable is that the listName is of type fieldNameType

How do I test for a lookup list item, and add it if it is missing, in SharePoint 2007 via C#?

Hi and thanks for looking!
Background
I am having trouble when I attempt to add a value to a lookup column.
I am using SharePoint 2007 and the app has to run in .NET 2.0. The language is C#. Some lookup columns will allow multiple values.
Question
Using C#, how do I do #'s 2-4 of the following:
Attempt to add a list item to a SP list.
For any lookup columns, check the SP List they are referencing to see if that list contains the value I am attempting to add.
If the value DOES NOT exist in the lookup list, add it.
Associate the newly added lookup value to the list item I was originally trying to add.
I have been googling this, of course, but am still stuck. Here is some code from Microsoft which is a start, but it is still not getting me going (not commented and not intuitive to me):
namespace ConsoleApp
{
class Program
{
static void Main(string[] args)
{
using (SPSite site = new SPSite("http://localhost"))
{
using (SPWeb web = site.RootWeb)
{
SPList customerList = web.Lists.TryGetList("Contoso Customers");
SPList orderList = web.Lists.TryGetList("Contoso Orders");
if (customerList != null && orderList != null)
{
SPListItemCollection customers = customerList.Items;
SPListItemCollection orders = orderList.Items;
string fieldName = "CustIDLookup";
if (!orderList.Fields.ContainsField(fieldName))
return;
SPField lookupFld = orderList.Fields.GetField(fieldName);
foreach (SPListItem customer in customers)
{
SPListItem order = orders.Add();
order[SPBuiltInFieldId.Title] = "Thank you!";
order.Update();
SPFieldLookupValue value = new SPFieldLookupValue(customer.ID, customer.ID.ToString());
order[lookupFld.Id] = value.ToString();
order.Update();
}
}
}
}
}
}
}
Even with Microsoft's examples, I can't get any real traction in figuring out how to actually do this.
Your help is GREATLY appreciated.
//untested pseudocode - hope this points you in the right direction
SPList lookupItems = ... // add code here
SPList list = ... // add code here
string lookupFieldName = "LookupValue"; // change to the appropriate value
foreach(SPListItem item in list.Items)
{
string value = (string)item[lookupFieldName];
if(value.Contains("#")) // value containing hash is most likely a lookup value already
{
// use SPFieldLookupValue to get actual value
SPFieldLookupValue currentValue = new SPFieldLookupValue(value);
value = currentValue.LookupValue;
}
// Get the list item (you will need this to find out its id value)
SPListItem lookupItem = GetLookupListItem(lookupList, value);
if(lookupItem == null)
{
//If it doesn't exist, create it
lookupItem = AddNewLookupItem(lookupList, value);
SPFieldLookupValue lookupValue = new SPFieldLookupValue(lookupItem.ID,value));
item["LookupValue"] = lookupValue.ToString();
item.Update();
}
}
SPListItem GetLookupListItem(SPList lookupList, string value)
{
// iterate through list to find item
// use a list query if the list is too big for this to perform well (see here: http://msdn.microsoft.com/en-us/library/ie/ms456030.aspx)
foreach(SPListItem item in lookupList)
{
string itemValue = (string)item[0]; // assuming lookup list has one field of type string containing lookup value
if(value == itemValue)
{
return item;
}
}
return null;
}
SPListItem AddLookupListItem(SPList list, string value)
{
SPListItem newItem = list.Add();
newItem[0] = value;// assuming lookup list has one field of type string containing lookup value
newItem.Update();
}

Categories