I have a list object
List<Documents>
, and inside that I have another list list of accounts.
List<Accounts>
From my codebehind I connect List to a repeater control
rptDocumentListings.DataSource = List<Documents>;
rptDocumentListings.DataBind();
While the repeater loops thru each item in List I want it to also loop thru each nest list of accounts, and then render out with tags. Here is what I've tried so far:
//in the dataRepeater
<%# parseAccountNumbers(Eval("Accounts"))%>
//method in codebehind
public string parseAccountNumbers(List<Account> accounts)
{
string allAccounts = string.Empty;
foreach (var item in accounts)
{
allAccounts += string.Format("{0}<br />", item.AccountNumber);
}
return allAccounts;
}
The error I get is 'Cannot convert from from 'Object' to 'System.Collections.List'
Can someone please point me in the right direction? Thanks in advance.
Change
<%# parseAccountNumbers(Eval("Accounts"))%>
To
<%# parseAccountNumbers((List<Account>)Eval("Accounts"))%>
DataBinder.Eval returns an Object and your method expects a List<Account>.
Another idea: instead of parseAccountNumbers(...)Create a public property (if possible) inside Documents class like:
public string AccountNumbers
{
return Accounts.Aggregate("", (current, account) => current + (account.AccountNumber + "<br/>"));
}
and use it as a datafield like:
<asp:Boundfield DataField="AccountNumbers" HeaderText="Account#" />
Related
I have an Images table linked to an Item table (one Item can have many Images). They are linked by the Item Id.
I want to return all images for an Item on the details page. I have been trying to use a Viewbag to achieve this (below).
Controller:
ViewBag.imageFile = (from f in storeDB.Images
where f.ItemId == id
select f.ImageURL).ToList();
View:
#foreach (var image in ((List<string>)ViewBag.imageFile))
{
#ViewBag.imageFile
}
The above will return 'System.Collections.Generic.List`1[System.String]' for each ImageUrl.
I believe the issue is that an object is being return rather than the actual List item string value but cannot figure out how to convert it to the string I need. The plan is to edit this foreach to create an img link for each URL.
I also have the following Viewbag (testing to see I was able to get the Urls at least):
ViewBag.imageURL = string.Join(",", ViewBag.imageFile);
The above returns the correct URLs but they are all in one string separated by a comma.
Appreciate any help.
Inside the loop in the view, you should use the loop variable:
#foreach (var image in ((List<string>)ViewBag.imageFile))
{
#image
}
ViewBag.imageFile is the complete list and will always be, even inside the loop. The image loop variable will be the current item from the list on every turn of the loop.
ViewBag does not require a type casting:
#foreach (var image in ViewBag.imageFile))
{
#image
}
I have a ListView in the itemDetailPage and I would like to share the selected item via e-mail. For which, I need to get the selected item from that listview.
What I tried is
if(listview1.SelectedItems.Count==1)
{
var item = listview1.SelectedItem
}
But I dont get the name, I get only the place it is taken from. Any suggestions?
Use Count instead of count. C# is case sensitive.
if(listview1.SelectedItems.Count == 1)
{
var item = listview1.SelectedItems[0].ToString();
}
Try this. You need to cast SelectedItem with your model class.
if (listview1.SelectedItems.Count==1)
{
var item = listview1.SelectedItems[0] as Node
}
I must bind a gridview to a method which returns list<>, there are few multi select lookups in the list, for this I have a method which returns dictionary<int, string>.
In the list I have the multi select item values as {1, xyz}, {2, abc}
So I must display in the grid as xyz, abc.
For this I have written a method FormatString which is called in gridview binding.. i.e aspx page
<%# FormatString(?????????) %>
I must pass list<> in the ???? to retreive the data..
Please suggest me some solutions..
'<%# FormatString(Container.DataItem as YourListType) %>'
public String FormatString(YourListType listObj )
{
//do what you want.
}
You can try this way
Get the values to a different list from your dictionary items
var items = yourDictionary.Values.SelectMany(x => x).ToList();
Then you can simply bind the list to gridview
Hi I am developing using the SharePoint namespace and I ran into the following error when I try to retrieve a Title field from the list items.
Value does not fall within the expected range
I know however that the field exists because I printed out all the fields.
string value = (string)listItem[listItem.Fields["Title"].Id];
Console.WriteLine("Title = " + value);
Update: To what extent does the View that was used to retrieve the list items play a role in what fields will be available? This code fails with the same exception:
SPListItemCollection items = list.GetItems(list.DefaultView);
foreach (SPListItem listItem in items)
{
try
{
Console.WriteLine("Title = " + listItem.Title);
}
catch (Exception e)
{
Console.WriteLine("Exception: " + e.Message);
}
}
In both cases the list.DefaultView property was used to retrieve the list items.
I don't know if your error is solved or not. But I was facing the same issue and I found the solution to the problem.
You have to go to:
Central Administration > Application Management > Manage Web Applications
select the Web Application in use and choose:
“General Settings > Resource Throttling” via the Ribbon.
In that scroll down and look for "List View Lookup Threshold" in that by default value is 8 increase the value till the error is gone.
Reference Link
I had this issue because the column was not part of the default view. Instead of relying on the view, query for the specific columns directly when creating the SPListItemCollection.
SPList cityList = web.Lists[cityListName];
SPListItemCollection items = cityList.GetItems("Title","LocCode");
foreach (SPListItem item in items)
{
cityName = item["Title"].ToString().Trim();
cityCode = item["LocCode"].ToString().Trim();
}
The "Title" field may exist in the list but not in the default view.
Can you do this?
foreach (var item in list.Items) Console.WriteLine((string)item["Title"]);
I'd suggest something like
if (item.Fields.ContainsField("Last_x0020_Modified"))
{
if (query.ViewFields.Contains("Last_x0020_Modified"))
...
B/c if the field wasn't requested in the SPQuery.ViewFields, you probably can't get it (exceptions include Created field, ID field)
The "Title" field is not (by default) available in the default view. If you have a look at the view settings page, Title is checked, but it is labeled as being "linked to item with edit menu".
The field exposed by the view is actually named "LinkTitle" (you can confirm this by enumerating list.DefaultView.ViewFields).
The solution to your problem is simply to replace item.Title with item["LinkTitle"].ToString().
I don't know why, but I created a GridView from SPListItemCollection as a DataSource. I had the same error. But I tried to get the dataTable from collection:
SPListItemCollection res = da.getAllItems();
DataTable dt = res.GetDataTable();
And then I see in my GridView that field that contains titles of list items is called "LinkTitle". So, I rewrited my code:
SPListItemCollection res = da.getAllItems();
gridView.DataSource = res.Cast<SPListItem>().Select(a=> a["LinkTitle"] );
gridView.DataBind();
And everything works fine :)
This problem can occure if you rename an already existing Column. Try deleting it and create a new one with the same name.
Or in another case that occured to me, I had accidentally wrote a letter of the column name in Greek! eg. "ΙsCooperation" Ι was a greek character
A few days ago, I wrote about issues with implementing a ListView in ASP.NET. Now, with all of the other code written, I'm having trouble saving changed items in a ListView.
A few things of note:
The Save button is not part of the ListView proper; it calls the GetListViewItems() method, which in turns call the Save() method.
The Listview.DataBind() event is invoked when a button is pressed requesting the records to be updated
The Listview shows text using <%#Eval("Key.Name") %> and a named DropDownList using <%#Eval("Value") %>
Getting The Items From the ListView
public void GetListViewItems()
{
List<Foo> Result = FooManager.CreateFooList();
DropDownList ddl = null;
ListViewItem Item = null;
try
{
foreach (ListViewDataItem item in lvFooList.Items)
{
Item = item;
ddl = ((DropDownList) (Item.FindControl("ddlListOfBars")));
if (//something is there)
{
Foo foo = FooManager.CreateFoo();
foo.Id = item.DataItemIndex; //shows null
int barId = int.Parse(ddl.SelectedItem.Value); //works just fine
foo.barId = barId;
Result.Add(foo);
}
}
}
catch (Exception ex)
{
//Irrelevant for our purposes
}
}
DataBinding the ListView
The code to databind the ListView is shown here in my previous question.
Question(s):
Why is it that when I iterate through the ListViewDataItem in the Listview that each item is null?
How can I retrieve the Foo.Id from the Dictionary?
What else might I be missing?
What would I use if I wanted to get that Id Programmatically based on what items were shown? As it is now, the current ListView is shown based on what Foos were selected. Those Foos selected are then displayed, and the user can change the Bar in the DropDownList, hit Save, and those changes are propogated.
Update
As it turns out, my problem was what leppie had said; and that was that I needed to specify DataKeyNames and use those to retain the information from the ListView.
Here's the code I added:
try
{
int DataKeyArrayIndex = 0;
foreach (ListViewDataItem item in lvFooList.Items)
{
Item = item;
ddl = ((DropDownList) (Item.FindControl("ddlListOfBars")));
if (//something is there)
{
Foo foo = FooManager.CreateFoo();
Foo tempFoo = FooManager.CreateFoo();
if (lvFooList != null)
{
tempFoo = ((Foo)(lvFooList.DataKeys[DataKeyArrayIndex].Value));
}
foo.Id = tempFoo.Id;
int barId = int.Parse(ddl.SelectedItem.Value); //works just fine
foo.barId = barId;
Result.Add(foo);
DataKeyArrayIndex++;
}
}
}
And then in the .ascx file, I added DataKeyNames="Key", like so:
<asp:ListView ID="lvFooList" runat="server" DataKeyNames="Key">
This allowed me to use the Key from my previous post to determine which Foo was being looked at.
Any critiques of this approach, as well as methods for making it better are greatly appreciated.
Some quick answers:
Your need to use databinding for that to work, in other words, assign to DataSource and call DataBind(). EDIT: seems you are doing that. But remember it wont persist between postbacks, just the DataKey (see below).
If I recall correctly, you need to specify the DataKeyNames, and they can be retrieved from the DataKey property then.
you can also use the ListViewDataItem.DataItemIndex property instead of keeping your own index, as in:
foreach (ListViewDataItem item in MyListView.Items)
{
// in this example key is a string value
Foo foo = new Foo(MyListView.DataKeys[item.DataItemIndex].Value as string);
// do stuff with foo
}