Iterating System.Collection.Generic.List.Add Does Not Work As Expected?

Mar 7, 2010

I was building an application for a project with .NET 3.5 and I noticed a weird behaviour of the List.Add method:

I have built my own class to organize data pulled from a database, and I use a while cycle to iterate through it.

However, when I List.Add(item), the whole content of the list is substituted with the last content pulled.

An example:

Suppose you have 3 users in a DB, each one identified with an ID and a username:

| ID | username |
| 1 | John |
| 2 | Fred |
| 3 | Paul |

and you have a "Users" class defined as

public class Users
{
private Int32 iD;
private String username;
public Int32 ID
{
get { return iD; }
set { iD = value; }
}
public String Username
{
get { return username; }
set { username = value; }
}
}

So you write this function:

[... SQL definitions - sdr is a SqlDataReader ...]
List<Users> userlist = new List<Users>();
if (sdr.HasRows) //There are users
{
Users user = new Users();
while (sdr.Read())
{
user.ID = sdr.GetInt32(0);
user.username = sdr.GetString(1);
userlist.Add(user);
}
}

What you expect (I expect) is userlist containing:

| ID | username |
| 1 | John |
| 2 | Fred |
| 3 | Paul |

What I actually get is, instead

| ID | username |
| 3 | Paul |
| 3 | Paul |
| 3 | Paul |

View 3 Replies


Similar Messages:

State Management :: Cache System.Collection.Generic.List Object?

Aug 22, 2010

I need to cache System.Collection.Generic.List object with expiration time

var Root = from feed in feedhotel.Descendants(ota + "HotelContent")
where (feed.Attribute("HotelCode") != null)
select new xmlhotel()
{
};
return Root.ToList();

Is it possible to cache Root.ToList() for some time....

View 1 Replies

C# - Cannot Implicitly Convert Type System.Collection.Generic.IEnumberable

Mar 8, 2010

I'm receiving this error in my Linq statement ---

Cannot implicitly convert type 'System.Collections.Generic.IEnumerable' to 'hcgames.ObjectClasses.ShoppingCart.ShoppingCartCartAddon'. An explicit conversion exists (are you missing a cast?)

From this query

ShoppingCartItems items = Cart.GetAllItems();
ShoppingCartCartAddons addons = Cart.GetAllAddons();
var stuff = from x in items
select new ShoppingCartItem()
{
ProductID = x.ProductID,
Quantity = x.Quantity,
Name = x.Name,
Price = x.Price,
Weight = x.Weight,
Addons = (from y in addons
where y.ShoppingCartItemID == x.ID
select y)
};

View 2 Replies

Web Forms :: Export A Generic List Collection To Excel File With Applying Styles

Oct 22, 2012

I need a list to export in excel and i need the following to achieve in the exported excell

-  I need the header of the excel with font bold and size should be 14px of font.

-  Other Cell try should be 12px of the font

- Right align the particular column in the excel

View 1 Replies

DataSource Controls ::collection Which Contains The Rows Shown Below In "Expected Result List"?

Mar 2, 2010

I have following two collections,1. CategoryList, 2. ItemList. I need to get the collection which contains the rows shown in below in "Expected Result List".could you please provide me the LINQ query on collections to get this resulted List?

[code]...

View 2 Replies

Data Controls :: Check If Data Exist In List Generic Collection Using C#

Apr 19, 2014

i want to check my collection so i can add a new customer as long as the username does not exist in the collection i do not want 2 customers to be able to have the same username.

i have been trying many different things to try to get this to work but i am not exactly sure what i should be doing I have a aspforum and collection C# class of the list.

here is some things that i have tried

CustomerExists()      i also have a collection of List<Customers>
 //HERE IS MY EXISTS METHOD
public static Boolean IfCustomerExists(string login) {
List<Customer> theGuy = Collections.Customers;
bool exist = false;
foreach (Customer customer in theGuy)

[Code]....

View 1 Replies

Forms Data Controls :: How To Bind Grid To Using System.Collections.Generic.List

Mar 25, 2011

I get this error when run the page

DataBinding: 'System.Int32' does not contain a property with the name 'item'.

protected void Page_Load(object sender, EventArgs e)
{
List<int> item = new List<int>();
{
item.Add(25);
item.Add(50);
item.Add(520);
item.Add(543);
item.Add(543);
item.Add(55);
};
GridView1.DataSource = item;
GridView1.DataBind();
}
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" ShowFooter="true">
<Columns>
<asp:TemplateField HeaderText="Sub total">
<ItemTemplate>
<asp:Label ID="subTotalLabel" runat="server" Text='<%#Eval("item")%>' />
</ItemTemplate>
<FooterTemplate>
<asp:Label ID="grandTotalLabel" runat="server" />
</FooterTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>

View 5 Replies

Difference Between Generic And Non - Generic Collection?

Oct 30, 2010

What is the difference between generic and non-generic collection?

View 1 Replies

System.InvalidCastException Iterating Through Viewdata

Jan 19, 2011

System.InvalidCastException iterating through Viewdata

I need to replace the code
"<%=Html.DropDownList("Part", (SelectList)ViewData["Parts"])%>"
for dropdown in the following manner for some reason.
<% foreach (Hexsolve.Data.BusinessObjects.HSPartList item in (IEnumerable)ViewData["Parts"])
{ %>
">
<%=item.PartName %>
<%=item.IssueNo %>
<% } %>

I am getting error converting SelectedList to IEnumerable) Error: Unable to cast object of type 'System.Web.Mvc.SelectList' to type 'System.Collections.Generic.IEnumerable`1[Hexsolve.Data.BusinessObjects.HSPartList]'. Is this the right way to iterate through viewdata[].

View 1 Replies

Custom Server Controls :: Using The Generic Type 'System.Collections.Generic.IEnumerable' Requires '1' Type Arguments

Nov 25, 2010

I'm trying to create a control out of a class I found, and one of the overridden functions is the following:

protected override void PerformDataBinding(IEnumerable data)

However, when I try to build the control I'm getting the error as shown in the subject. I've tried searching, and it seems the signature for the original function matches the one I have, and all other solutions I've seen uses the same signature.

View 3 Replies

BinarySearch() Not Locating Items In A Generic Collection?

May 14, 2010

When I dump the contents of a List<string>, I get:

Sue
Larry
John Barrowman
Bob

However, when I try to retrieve the index of the strings using this format...

thisIndex = blockRetrievedList.BinarySearch("Sue");

and print the indexes in an HTML list, here's the results that I get...

Using blockRetrievedList.BinarySearch('Larry'); : 1
Using blockRetrievedList.BinarySearch('Mike'); : -5
Using blockRetrievedList.BinarySearch('Sue'); : -5
Using blockRetrievedList.BinarySearch('Bob'); : -1
Using blockRetrievedList.BinarySearch('John Barrowman'); : -1

So while Larry comes out fine at index one, John Barrowman and Bob should be indexes 2 & 3 respectively. However, they're coming up -1 meaning they're not recognized as being the collection. Further Mike (who was originally in the set, but who has now been replaced by John Barrowman is coming up -5. Isn't that supposed to be -1? And why on Earth is Sue (who is index 0, returning -5 as well?

View 10 Replies

Binding GridView To Generic Collection Using TemplateField

Sep 16, 2010

I have GridView bound to some List. In layout I created following template field:

<asp:TemplateField HeaderText="Phrase">
<ItemTemplate>
<asp:TextBox ID="phraseTextBox" runat="server" Text='<%# Bind("Phrase") %>'/>
</ItemTemplate>
</asp:TemplateField>

But after changing the content of any TextBox in column "Phrase" my List doesn't reflect that changes.

View 2 Replies

Fluent Nhibernate System.ApplicationException : For Property 'Id' Expected '1' Of Type 'System.Int32' But Got '2' Of Type 'System.Int32'

Jul 6, 2010

I am writing unit tests for fluent Nhibernate, when I run the test in isloation it passes, but when I run multiple tests. or run the test more than once it starts failing with the message below System.ApplicationException : For property 'Id' expected '1' of type 'System.Int32' but got '2' of type 'System.Int32'

[TextFixture]
public void Can_Correctly_Map_Entity()
{
new PersistenceSpecification<UserProfile>(Session)
.CheckProperty(c => c.Id, 1)
.CheckProperty(c => c.UserName, "user")
.CheckProperty(c => c.Address1, "Address1")
.CheckProperty(c => c.Address2, "Address2")
}

View 2 Replies

List Collection That Contain A List Of Dictionary Collection - How To Use It

Feb 1, 2011

List<Dictionary <string,object>> I am reading about the list and collection, If possible, what are the different ways that I can utilize the list of dictionary collections..... gives me different examples or areas where I can use it.

View 3 Replies

Web Forms :: Adding List Items To Drop Down Control From Generic List?

Feb 6, 2010

I have the following Students class:

[Code]....

I need the 1 since it's a foreign key in another table. For the life of me, I can't get this to work like this.

View 7 Replies

AJAX :: OnClientClick Doesn't Work As Expected With UpdatePanel

Feb 2, 2010

I have an onclientclick property on a linkbutton that calls a javascript function.
inside Update Panel

[Code]....

iam getting the error at bold line . my listbox is inside Update Panel and link button too but java script is outside of Update Panel.

View 2 Replies

Javascript - Applying Background-color Property To A Div Does Not Work As Expected?

Jan 6, 2011

What do I have wrong here? This page is essentially broken into 5 divs, the middle 3 divs that represent the left, middle and right page columns are wrapped in a div with the id content. I linked to the page if you want to view the source. It wouldn't go in this message as a snippet very well when I tried.

Here is the style for #content

#content
{
background-color:White;
}

How do I get the whole background of #content to show as white? link to a live version of[URL]

View 4 Replies

Web Forms :: System.Web.Mail.SmtpMail.Send Raises Value Does Not Fall Within The Expected Range

Oct 8, 2010

I have a message (System.Web.Mail.MailMessage) whose body is 400 bytes long, nothing in cc or bcc, has valid to/from addresses. But when I get to System.Web.Mail.WebMail.Send(msg) I get the exception [HttpException (0x80004005): Value does not fall within the expected range.] Not sure where to look. Google only provided a handful of options, mostly related to CDO.

View 2 Replies

Web Forms :: Unable To Get The Expected Value From Drop Down List?

Mar 13, 2010

I have a drop down list that is populated with customer IDs. When I write to the db a value of 11 is written for the customer ID 13 when it is chosen from the drop down . I thought this was because I was using the SelectedIndex and how it is 0 based like an array. In the drop down list I choose 13. Id 2 is missing from the drop down list because that record was deleted. I thought these two things together explained the two digit discrepancy with the what i got when I used the Selected Index property. I then decided to use the SelectedValue property which should give me 13 when I choose 13 in the drop down list.

The same thing happens when I use the SelectedValue property. I used the SelectedValue property and chose 13 in the drop down list. This also gave me 11 as the value that was written to the db. This makes no sense to me. If I chose 13 in the drop down then 13 should have been written to the db when using the SelectedValue.

I'm using a Sql Data Source temporarily to populate this with the CustID.

[Code]....

View 2 Replies

Create Generic Class From System.Web.Mvc.ViewPage?

Apr 30, 2010

How can I create generic class from System.Web.Mvc.ViewPage?

View 1 Replies

MVC :: Method Not Found: 'System.Collections.Generic.IDictionary`2

Mar 10, 2010

I dont know what I have done but my add blog or news item functionality is broken. It works fine locally but not on the server (.net 3.5 mvc 2 I believe).

[Code]....

The interesting thing is the path P:Web_DevelopmentAHNDEVControllersAdministratorController.vb. This is my local path on my machine but not the

View 16 Replies

Trying To Use .Contains For Generic List

Jan 3, 2011

I have a list view control. Each row within it has a rowid and a textbox where a note(user enters relevant info to that particular record) is entered. On a paging event I store the rowID and the note text in a generic list for retrieval if the user pages back later on. Goal here is to keep the text the user has entered. (see the code below)This generic list does in fact get populated correctly when I go to the next page currently. I can see this in Visual Studio. So now, when the user goes back to the first page I want to run a test within my Listviews ItemDataBound event. I want to see if the row ID being tested is part of the generic list. If so, I then want to take the corresponding note that is also within the list and bind it to the text box. However, I don't know how to write the correct conditional for this and how to bind the textbox if the conditional evaluates to true.

View 1 Replies

The Model Item Passed Into The Dictionary Is Of Type 'System.Collections.Generic.Lis

May 2, 2010

Calling Index view is giving me this very very annoying error . Can anybody tell me what to do about it

Error:The model item passed into the dictionary is of type 'System.Collections.Generic.List1[MvcApplication13.Models.Groups]', but this dictionary requires a model item of type 'MvcApplication13.Helpers.PaginatedList1[MvcApplication13.Models.Groups]'.

public ActionResult Index(int? page)
{
const int pageSize = 10; [code].....

View 1 Replies

Merge To Generic List?

Apr 7, 2010

I have two generic list with Hotel class object. Both List contains hotel ID. I want to retrieve common hotel id from both Hotel List and assign to new HotelList.I have done following code for that but any other sort way to implement this kind of functionality.

[Code]....

Note: I dont want to use Linq because I am working on framwork 2.0

View 1 Replies

C# Generic List And ASP Repeater Fun

Aug 4, 2010

I'm trying to render out some images on an aspx page. Error I'm getting in the code below is:

DataBinding: '_Default+ImageThing' does not contain a property with the name 'FileName'.
public class ImageThing
{
public string FileName;
}
private void DisplayThumbnailImages()
{
ImageThing imageThing1 = new ImageThing();
ImageThing imageThing2 = new ImageThing();
imageThing1.FileName = "asdf.jpg";
imageThing2.FileName = "aaa.jpg";
List<ImageThing> imagesToRender = new List<ImageThing>();
imagesToRender.Add(imageThing1);
imagesToRender.Add(imageThing2);
Repeater1.DataSource = imagesToRender;
Repeater1.DataBind();
}

here is the aspx:

<asp:Repeater ID="Repeater1" runat="server">
<ItemTemplate>
<%#DataBinder.Eval(Container.DataItem, "FileName")%>
</ItemTemplate>
</asp:Repeater>

View 3 Replies







Copyrights 2005-15 www.BigResource.com, All rights reserved