Programmatically setting field value for sharepoint listitem - c#

I'm trying to simply add a simple text or hyperlink field to a list item in sharepoint 2007.
I can add the field no problem:
list.Fields.Add("MyField",SPFieldType.Text, false);
And it shows up fine on my list items.
However no matter which way I try, I can't programmatically set a value for the field. I tried:
list.items[0]["MyField"] = "text";
and I tried loading into a field:
SPField field = list.items[0].Fields["MyField"];
and setting it there, and setting the default value and updating, but nothing what so ever happens.
I always finish my code blocks with list.update(); or if I'm operating on the item itself item.update(); so I'm not at least missing that. Can anyone tell me what I'm doing wrong?
Thanks

Try:
SPListItem item = list.items[0];
item["MyField"] = "text";
item.Update();
Although it seems equivalent, the above code is not the same as:
list.items[0]["MyField"] = "text";
list.items[0].Update();
For more information, see here and here for people who have documented the same behavior.

Could you try this for adding a new field and setting a default value? Untested code. let me know how it goes.
SPFieldText fldName = (SPFieldText)list.Fields.CreateNewField(SPFieldType.Text.ToString(), "mycolumn");
fldName.DefaultValue = "default";
list.Fields.Add(fldName);
list.Update();

I've always found the best route is to get a reference to the list item directly and update specifically, as opposed to using the indexer route. Just like rich's first example mentions.
http://www.sharepointdevwiki.com/display/public/Updating+a+List+Item+programmatically+using+the+object+model

From all the discussion above it appears that you are trying to set the field value in a list event handler and you are setting the value in item adding or item updating event. If this is the case then you need to consider AfterProperties. Remember we have *ing and *ed events and in case of *ing events we need to work with BeforeProperties and AfterProperties.
I hope this helps!

Related

How do I get the current Editor of an Listitem while ItemUpdating?

how can I get the current Editor of an list Item in SharePoint 2010 during ItemUpdating?
Problem is properties.AfterProperties["Editor"].ToString() throws and Ecxeption cause it's null. This properties.ListItem["Editor"].ToString() is useless cause I get the Editor which made changes the last time.
Any guess how i can Achiev this during the Updating?
Ok found out that there is no way to get it this way.
this worked for me: properties.UserDisplayName
Check the internal name for the field Modified By
ListItem.ParentList.Fields ["Modified By"]. InternalName
It may be "_Editor" or else.

Trying to set the value of a Drop Down

I am trying to set the value or text of a drop down to a value being pulled by the database, this is being passed through an Entity and when I debug i see the right hand side part of the code has the string value i want to match on the drop down but still when I do a step in and goes to the next line the left hand side still selects the -- Select -- item
I am trying to assign it as follows
ddlMyDropDown.SelectedItem.Text = Clients.MerchandiseType.ToString();
WHEN STEPPING THROUGH IT
ddlMyDropDown.SelectedItem.Text contains "--Select --"
Clients.MerchandiseType.ToString() contains "Sporting Goods"
ddlMyDropDown has an Item named "Sporting Goods" but it never selects it when I use the code above , I am not sure why. Is there anyway to achieve this?
I am not trying to change change any values , but to set the ddlMyDropDown to the Text in Clients.MerchandiseType.ToString(). The drop down will always have the text being passed on Clients.Merchandise.ToString();
Thank you
Not sure of the method names at the moment as i'm not at a pc with visual studios but here's some hints.
var text = Clients.MerchandiseType.ToString();
var item = ddlMyDropDown.Find(text); //Some method that returns a list item
ddlMyDropDown.SelectedItem = item;
Hope this helps.
If theres not a better answer tomorrow I will post a full solution.
Try
ddlMyDropDown.SelectedIndex = Combox1.FindStringExact(Clients.MerchandiseType.ToString());
Not sure but I think you can't change the Selected Item by changing SelectedText.
You have to set
ddlMyDropDown.SelectedIndex = i
or
ddlMyDropDown.SelectedItem = item
Use one of the following:
ddlMyDropDown.SelectedValue = Clients.MerchandiseType.ToString();
OR
ListItem item = ddlMyDropDown.Items.FindItemByValue(Clients.MerchandiseType.ToString());
if (item != null)
item.Selected = true;

"All" value for a Combobox Data Filter in WPF

During the construction of user control I populate the combobox with some data. Works fine. I have Status.ID as valuePath and Status.Name as displayPath.
cmb.ItemsSource = dbEntities.Status
The comobox will be used as a filter control and I need to insert some value for "All", which will be used as the empty filter.
First I tried a funny solution:
ObjectSet objectSet= dbEntities.Status;
Status stAll = new Status();
stAll.ID = -1;
stAll.Name = "All";
objectSet.AddObject(stAll);
cmb.ItemsSource = objectSet;
For some reason the object is not added to the objectSet. It didnt throw any exception either.
Then I tried to insert it manually to the first index but I got the error:
"Operation is not valid while ItemsSource is in use. Access and modify elements with ItemsControl.ItemsSource instead."
My code looked like:
cmb.ItemsSource = entities.Status;
cmb.Items.Insert(0,"All");
Both didnt work. What would be the easiest way to add that line to the combobox? The error message got me confused. I am not sure how to use the ItemsSource for such a purpose.
edit: I did not have enough rep to answer my own question so here is the working code. Thanks Craig again.
CompositeCollection comp = new CompositeCollection();
comp.Add(new CollectionContainer {Collection = dbEntities.Status});
Status stAll = new Status();
stAll.ID = -1;
stAll.Name = "All";
comp.add(stAll);
cmb.ItemsSource = comp;
//do whatever filter you want when the selected value is -1
There are a couple different problems with what you are trying to do. You can't manipulate the Items when you are using the ItemsSource, instead you have to go through the object that is set to the ItemsSource. That is what the error message is about in the second part. Its because when you set the ItemsSource the Items value is unused it is not populated with the values of the ItemsSource.
I'm not familiar enough with the ObjectSet class to know why the first case is not working. However, it seems awkward to add an item to your values you are pulling from somewhere else, just to have the all case. The better solution is to use a null value to represent nothing. Unfortunately, there is no built in way to do this in WPF. However, there is a fairly easy solution of using an Adaptor do do this. I have used this solution a NullItemSelectorAdaptor, that enables null as a selection even if null is not in the list. All you have to do is wrap your combobox in the NullItemSelectorAdapter and null will be added as a value. The blog post explains everything pretty clearly, so I won't repeat it. You than can setup your filter so that null equates to no filtering.

ASP.NET DropDownList Replacement

Currently, I'm populating a drop down list when a file is created in a configurable folder.
if (!downloadRspDropDown.Items.Contains(new ListItem(txt, fileData.FullName))
Then, I add the file and remove "No Responses Available".
However, if the same file is resubmitted (i.e., the file name is the same but the timestamp is different), then I want to remove the older entry and replace it with a new entry in the drop down list.
I have the filename, so I go into the "else" block from the line of code above. From there, I'm checking to see if I have the same filename and a different creation time.
if (downloadRspDropDown.Items.Contains(new ListItem(txt, fileData.FullName) &&
downloadRspDropDown.Items.Contains(new ListItem(txt, fileData.CreationTime)
From here, I want to find the position, remove it, and add the new text. This approach isn't working. Can anyone offer an alternate approach?
I dont know if that is your current problem, but this line is definitly causing trouble:
if (!downloadRspDropDown.Items.Contains(new ListItem(txt, fileData.FullName))
What you probably want to achieve is a check for equality based on a value. But this line of code performs an equality check based on a reference and can't be true, because you create a new ListItem that definitly has another reference than the item already added to the Dropdownlist.
Try to use the .FindByValue method instead.
Edit based on comment:
Try something like this:
ListItem _li = downloadRspDropDown.Items.FindByValue(fileData.FullName);
if(_li != null)
{
downloadRspDropDown.Items.Remove(_li);
}

Set "Target Audiences" field with multiple values on a List Item

I am attempting to set the "Target Audiences" field on a list item programmatically. I have been able to set the value programmatically for one audience, but when I attempt to use multiple audiences, SharePoint tries to interpret the value I am setting as a single audience, rather than multiple. I am setting the value using the code below.
listItem[listItem.Fields["Target Audiences"].InternalName] = "Audience One";
I use this code to specify multiple audiences like so:
listItem[listItem.Fields["Target Audiences"].InternalName] = "Audience One; Audience Two";
When I do this, SharePoint tries to interpret the entire string as a single audience, and I get a message when I edit the list item that says "No exact match was found."
Am I using the correct format for specifying multiple audiences for this field, or is there a class that I should be using similar to SPFieldLookupValue?
I don't know how to save multiple audiences in a SPListItem, but if I had this problem, I'd try to print out the value of this field from a PowerShell script. Something like:
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint");
$site = Microsoft.SharePoint.SPSite("http://yourserver");
$web = $site.openweb();
$list = $web.lists["YourList"];
$item = $list.getitembyid(itemid);
write-output $item["Target Audiences"];
EDIT: found some information about what the Audience field value actually is: http://dotnetmafia.sys-con.com/node/1181567/mobile
Just realized I never came back and answered this.
I ended up storing the names of the audiences in a column attached to each list item, then querying the object model to see if the current user is a member of those audiences. This worked for me because I was pulling the data from the list item in a custom web part, and the user never saw the actual list item.

Categories