Wednesday 15 June 2011

c# - assign data from LINQ to ArrayList -



c# - assign data from LINQ to ArrayList -

unable cast object of type '<>f__anonymoustype0`7[system.int32,system.string,system.string,system.string,system.string,system.string,system.int32]' type 'mywebapplication.tblmywebsite

i'm newbie c# here tell me what's problem in code please?

anonymoustype0 when need records linq sql , show browser using arraylist.

see code please

using system; using system.collections; // can utilize arraylist. using system.text; // can utilize stringbuilder. using system.collections.generic; using system.linq; using system.web; using system.web.ui; using system.web.ui.webcontrols; namespace mywebapplication { public partial class webform2 : system.web.ui.page { protected void page_load(object sender, eventargs e) { showproducts(); } private void showproducts() { dbdatacontext db = new dbdatacontext(); var products = p in db.tblmywebsites select p ; gridview1.datasource = products; gridview1.databind(); // way convert linq query arraylist arraylist myarrlist = new arraylist(); myarrlist.addrange((from p in db.tblmywebsites select new { p.id, p.productname, p.tblprogramminglanguage.programminglanguage, p.tblapplicationtype.applicationtype, p.image, p.review, p.price}).tolist()); // stringbuilder represents mutable string of characters. stringbuilder sb = new stringbuilder(); foreach (tblmywebsite myproduct in myarrlist) { sb.append(string.format(@"<table class = 'coffeetable'> <tr> <th>id: </th> <td>{1}</td> </tr> <tr> <th>productname: </th> <td>{2}</td> </tr> <tr> <th>programminglanguage: </th> <td>{3}</td> </tr> <tr> <th>type: </th> <td>{4}</td> </tr> <tr> <th>image: </th> <td>{5}</td> </tr> <tr> <th>review: </th> <td>{6}</td> </tr> <tr> <th>price: </th> <td>{7}</td> </tr> </table> ", myproduct.id, myproduct.productname, myproduct.programminglanguage, myproduct.type, myproduct.image, myproduct.review, myproduct.price).tostring()); } } } }

you populating array list anonymous types here:

myarrlist.addrange((from p in db.tblmywebsites select new { p.id, p.productname, p.tblprogramminglanguage.programminglanguage, p.tblapplicationtype.applicationtype, p.image, p.review, p.price}).tolist());

but seek , this:

foreach (tblmywebsite myproduct in myarrlist)

your array list doesn't contain tblmywebsite objects, contains anonymous types. if have same fields same names, won't convert them automatically. assumption tblmywebsite database (in other words, db.tblmywebsites collection of tblmywebsite objects). can simply:

myarrlist.addrange(db.tblmywebsites); // array list populated // tblmywebsite objects

there no need utilize select unless need alter or remap something. there's no real point in using arraylist, generic list<t> much easier use. could, in fact, do:

foreach (var myproduct in db.tblmywebsites)

c# linq

No comments:

Post a Comment