Sharepoint calculated field in lookup field - c#

I'm having trouble accessing the value of a calculated field from a list which is in a lookup field on another list in codebehind for SharePoint.
A ListFieldIterator on a page displays a load of options to a user. I need to perform some back-end validation on some particular selections the user has made.
I have a list called "Event Type" from which a user can select Play, performance, display etc. This list has 4 columns - description, enabled, default and filtered. Filtered is a calculated column which is generated based upon the options chosen on the other columns.
The list Events has a column which is a lookup to this list, and which displays the filtered column.
Now on the page this all works great. The options are displayed to the user and they can make their selection. Before adding the calculated field I could access the choice made by doing the below
SPFieldLookup eventTypeField = ListFieldIterator.Item.Fields.GetField("Event_x0020_Type") as SPFieldLookup;
if (eventTypeField.GetFieldValueAsText(ListFieldIterator.Item["Event_x0020_Type"]) == "Performance")
{
// some other logic
errorMessages.Add("There is an error here");
}
Now however when accessing the field in this way I just get an empty string back.
If I attempt to access the chosen item with
string value = eventFields.Item["Event_x0020_Type_x0020_1"].ToString();
Then I get back "8" which is the position in the list of the item I chose. (it changes based on what item in the list I select)
This post Get value of calculate field seems related but I can't see an obvious way to get a calculated field from the lookupfield.
Any suggestions appreciated

It turns out that when using either a lookup column or a lookup column with a calculated field in, as I was, I was going about things the wrong way. This post put me onto the solution. The code is also below.
Essentially I need to access the value stored in the control of the ListFieldIterator and not the value from the item. The code below (from the link above) provides a nice way to do this.
public static List<T> GetControlsOfType<T>(this ControlCollection controls)
{
List<T> resultList = new List<T>();
foreach (Control control in controls)
{
if (control is T)
resultList.Add((T)((object)control));
if (control.Controls.Count > 0)
{
resultList.AddRange(GetControlsOfType<T>(control.Controls));
}
}
return resultList;
}
public object GetFieldValue(ListFieldIterator lfi, string fieldName)
{
FormField formField = lfi.Controls.GetControlsOfType<FormField>().Where(f => f.FieldName == fieldName).FirstOrDefault();
if (formField == null) return null;
return formField.Value;
}

Related

Filtering Children in Entity Framework Query

I have a database which it's schema is as follows:
As you can see, We have WareCategories which will be category of the wares i'm going to be working in my website. WareTypes which will be Definition of each Item type. Categories define properties in the table WarePropertyDefinitions and WareProperties define values for each property that has been defined in WarePropertyDefinitions table.
Now i have a search page that users search for items in OldWares and user selects category and i show the user all properties defined in WarePropertyDefinitions and user fills the data if he likes better results. But my problem is that i can't filter WareTypes based on WareProperties because it's from the type ICollection and i can't access filter options.
How can i apply this kind of filtering based on properties?
Thanks in advance...
Edit:
This is a part of the code i'm presenting to describe more:
var lst = WareCategory.GetItem(Convert.ToInt32(ddlChildren.SelectedValue)).WarePropertyDefinitions.ToList();
foreach (var ListItem in lst)
{
var value = BaseHelper.FindFormValue("PropertyValue" + ListItem.Id.ToString());
if (!string.IsNullOrEmpty(value))
{
query = query.Where(m => m.WareType.WareProperties.);
}
}
}
This segment of code is in my search function and as you can see i'm going to generate a list of items in WarePropertyDefinition that user selected via a drop down menu called ddlChildren. I'm going to iterate in this definition and user entered value for each property (the value variable will hold the value user entered and i will check if user have entered anything in the textbox) i will include it in where section (through this i will add it in where clause that ultimately filters my selection). but as you can see the code is incomplete because i don't know how to complete it.
Use the Any() extension method, for example:
query = query.Where(m => m.WareType.WareProperties.Any(wp => wp.Id == 5));
I have fixed the my problem by this code:
query = query.Where(m => m.WareType.WareProperties.Any(wp => wp.WarePropertyDefinition_Id == ListItem.Id && wp.TextValue == value));
but because #user3159792's answer was the basic of my problem i have selected his answer as the default answer to my problem. very thanks.

How to get multiple selected values from listbox C# Windows Application

I am using a Listbox on my windows application. The listbox has a multi-selection option, which users select all the roles the new user will have.
My Listbox is bound to a dataset. The table is Roles, with an ID column and Description column.
When I bound the listbox, I chose the data source being the dataset, the display member to be the description, the value member being the ID and the selected value being the dataset - roles.frolesid
Now when i loop through the listbox's selecteditems, i get only the first item's values etc...
I am trying to assign an int to the current selectedvalue, to get the ID to give to the user.
int num = 0;
foreach (var item2 in lstRoles.SelectedItems)
{
num = Convert.ToInt32(lstRoles.SelectedValue);
}
So if I select 3 roles, for instance Administrator, Capturer and Assessor, I only see the Administrator value.
How do I loop and access the next item? I'm not even using
item2
in my code. Could this be utilised?
For instance:
First iteration:
And it just stays on that selected item, never moving to the next item.
To get list of selected values when the data source is a DataTable, you can use this code:
var selectedValues = listBox1.SelectedItems.Cast<DataRowView>()
.Select(dr => (int)(dr[listBox1.ValueMember]))
.ToList();
But in general Item of a ListBox control may be DataRowView, Complex Objects, Anonymous types, primary types and other types. Underlying value of an item should be calculated base on ValueMember.
If you are looking for a good solution which works with different settings and different data sources, you may find this post helpful. It contains an extension method which returns value of an item. It works like GetItemText method of ListBox.
solved it
int num = 0;
int count = fRoleIDs.Count;
while (num != count)
{
var item = lstRoles.Items[num] as System.Data.DataRowView;
int id = Convert.ToInt32(item.Row.ItemArray[0]);
num += 1;
}
This goes into the listbox's items and according to the index, gets the item as a Row. This then gets me the itemarray, which is ID and Description {0,1}

How to filter a lookup field in Sharepoint?

I have a list "Contracts", it has two columns - "Title" and "Status". Status is a choice field which can be either "Active" or "Closed".
I have another list, in which I create a lookup field "Contract", which gets populated by records from the "Title" column in the "Contracts" list.
Now, I need to make it get populated only by those titles that have an active status.
So far I have this
SPList contractList = web.Lists.TryGetList("Contracts");
if (contractList != null)
{
myList.Fields.AddLookup("Contract", contractList.ID, false);
SPFieldLookup lookup = (SPFieldLookup)taskList.Fields["Contract"];
lookup.LookupField = contractList.Fields["Title"].InternalName;
lookup.Update();
}
Obviously, it gets all the titles from the "Contracts" list. Is it possible to filter it, to only show the ones with the "Status" field equal to "Active"?
You could use query to filter the data at the time of retrieval from list..
this might help you:
http://msdn.microsoft.com/en-us/library/ms457534.aspx

problem with drop down list

I have a drop down list control populated with items and some code to take the currently selected item value. The problem is I only get the value of the first item in the list regardless of what item is actually selected.
Here is my code to populate the drop down:
protected void displayCreateCategories()
{
StoreDataContext db = new StoreDataContext();
var a = from c in db.Categories
orderby c.Name
select new{catName= c.Name,
catId=c.CategoryID};
ddlCategory.DataSource = a;
ddlCategory.DataTextField = "catName";
ddlCategory.DataValueField = "catId";
ddlCategory.DataBind();
}
To get the value of the currently selected item which in my case is always of type integer I do label1.text=Convert.toInt32(ddlCategory.SelectedValue);
I get the selected value, but it is always for the 1st item in the list. I'm pulling my hair out over this. :(
I suspect you're running the list loading code every time the page loads, which is destroying the list, repopulating the list, and auto-selecting the first item before your selection retrieval code gets run.
Use this construction in Page_Load:
if (!IsPostBack)
{
// Initial control population goes here
}
Data binding will reset the control's selected value so make sure you retrieve the selected value before data binding on postback.

Insert/Update multiple lookup values to an SPListItem

My SharePoint list has a column that allows multiple lookup values. My C# control (within a webpart) allows the user to make multiple selections from a list box. I split these values into an array - each array member being a selected value that needs to be updated in the same SPListItem column.
I know that the selections are being passed in properly from the list box - I just need to add this group of values to the same column in the SPListItem.
Where am I going wrong?
SPFieldLookupValueCollection MyCollection = new SPFieldLookupValueCollection();
for (int i = 0; i < MyArrayOfSelections.Length; i++)
{
if (MyLookupList["LookupColumn"].ToString() == MyArrayOfSelections[i].ToString())
{
MyID = int.Parse(MyLookupList[i]["ID"].ToString());
SPFieldLookupValue thisSelection = new SPFieldLookupValue(MyID,MyArrayOfSelections[i].ToString());
MySubCollection.Add(thisSelection);
}
}
ListIWantToUpdate["ColumnWithMultipleLookupSelections"] = SubCollection;
ListIWantToUpdate.Update();
site.Update();
}
The last rows of the code example are confusing (maybe it's just variable naming). If you are just updating the data, you never need to update neither the SPList object (this requires "Manage lists" permission on the particular list, nor SPSite ojbect (requires you to be site administrator or owner). So, this code will not run succcessfuly for a regular user.

Categories

Resources