convert arraylist into IList in vb.net - asp.net-mvc

I am getting an arraylist in view from controller. In view when i try to display that array error occur "Unable to cast object of type 'System.Collections.ArrayList' to type 'System.Collections.Generic.IList`1". my code is as below
Dim c As IList(Of myclass) = CType(Model, IList(Of myclass)) (arraylist from controller)
In Model there is an arraylist. I don't know how to cast this arraylist into IList. Please help. Thanks
Dim iplist = (From d In db.mytable Select d).ToList
Dim c2 As ArrayList
For i As integer = 0 to iplist.Count - 1
Dim ip = iplist(i).ip
Dim c as countrylist
c.country = country
c.city = city
Next
Class cou1ntrylist
Public country As String
Public city As New ArrayList
End Class

Related

How to Fill Drop Down List using Model in MVC

Function GetStateName() As List(Of SelectListItem)
Dim ListRoomMaster As List(Of MiscMaster) = New List(Of MiscMaster)
Dim rm As New MiscMaster
Using conn As New SqlConnection(connectionString)
Dim sSql = "Select * From dropdown"
Dim cmd As SqlCommand = New SqlCommand(sSql, conn)
conn.Open()
Dim rst As SqlDataReader = cmd.ExecuteReader
Do While rst.Read
rm.m_ddlId = rst!id
rm.ddlValue = rst!name
ListRoomMaster.Add(rm)
Loop
End Using
Dim Listxyz = (
From p In Enumerable.Range(0, 20)
Select New SelectListItem With {.Text = p.ToString(), .Value = p.ToString()})
Return Listxyz.ToList()
End Function
This is the code for GetStateName() Which I am calling from controller Before Viewing This Displays The Drop Down List With 0 to 19 numbers I know I have Miss Something But Don't Know Where to change as most of code are for Linq
This Is Controller Code
Function Index() As ActionResult
objMisc.StateValue = objMisc.GetStateName()
'objMisc.StateValue = obj
Return View(objMisc)
End Function
What I Exactly Want Is Fetching data from DataBase using query
DataBase Have field like follow
id | Value
1 | xyz
2 | abx
3 | kvd
I want to populate drop down List As xyz,abx,kvd
And when abx is selected I want to store 2 in database
If you are working with MVC then you can also get the Data directly in the Razor View from your Model. Because you are doing a SQL Query manually which isnt the puropse of MVC.
Your should return the Model and then you can simply do this:
#Html.DropDownListFor(m => m.column, Model.dropdown)
Let's make a couple of models:
public NameCode(string name)
{
Name = name;
Code = name;
}
public NameCodeCollection(IEnumerable<NameCodeItem> list) : base(list)
{
}
In razor:
#Html.DropDownListFor(m => m.modelid, new SelectList(Model.modeltext, "Name", "Code"))
Use the namecodecollection to feed your dropdown list & read from it.

Unable to cast object of type 'System.Collections.Generic.List TO System.Collections.Generic.IList

I have the following code :
public class ComputeOperationData
{
public COUNTERS_DATA CounterData { get; set; }
public COMPUTES_OPERATION ComputeOperation { get; set; }
public COUNTERS_FORMULA CounterFormula { get; set; }
}
Public Function GetComputeOperationData(ByVal computeId As Integer, ByVal priodType As Integer, ByVal lstDuringTime As DuringTime) As IList(Of ComputeOperationData) Implements IComputeResultService.GetComputeOperationData
Dim computeOperations As IQueryable(Of COMPUTES_OPERATION) = _repository.GetObjectQuery(Of COMPUTES_OPERATION).Include("COMPUTES").Include("COUNTERS")
computeOperations = computeOperations.Where(Function(a) a.COMPUTE_ID = computeId)
Dim countersFormula As IQueryable(Of COUNTERS_FORMULA) = _repository.GetObjectQuery(Of COUNTERS_FORMULA)().Include("COUNTERS")
Dim countersData As IQueryable(Of DomainClasses.COUNTERS_DATA) = _repository.GetObjectQuery(Of DomainClasses.COUNTERS_DATA)().Include("COUNTERS")
countersData = countersData.Where(Function(a) a.PERIOD_TYPE = priodType And a.COUNTER_DATE = lstDuringTime.StartDate And a.COUNTER_TIME >= lstDuringTime.StartTime And a.COUNTER_TIME <= lstDuringTime.EndTime)
Dim lstComputeOperationData = From counterData In countersData
Join computeOperation In computeOperations On counterData.COUNTER_ID Equals computeOperation.COUNTER_ID
Join counterFormula In countersFormula On counterData.COUNTER_ID Equals counterFormula.COUNTER_ID
Where counterData.COUNTER_DATE >= counterFormula.FROM_DATE And counterData.COUNTER_DATE <= counterFormula.TO_DATE
Return lstComputeOperationData.ToList
End Function
And I got this error :
Unable to cast object of type 'System.Data.Objects.ObjectQuery1[VB$AnonymousType_13[Danesh.Ems.DomainClasses.COUNTERS_DATA,Danesh.Ems.DomainClasses.COMPUTES_OPERATION,Danesh.Ems.DomainClasses.COUNTERS_FORMULA]]' to type 'System.Collections.Generic.IList`1[Danesh.Ems.Models.ComputeOperationData]'
please help me
It's been a while since I used VB.NET, but in C#, you'd need something like...
Select New ComputeOperationData()
{
CounterData = counterData, ComputeOperation = computeOperation, CounterFormula = counterFormula
}
...at the end of your query to transform the three separate data sources into a single object.
You have function that return IList(Of ComputeOperationData) but inside you tru return List(Of AnonymousClass)
so in your linq query you need specify what type of object you want return, like this
Dim lstComputeOperationData = From counterData In countersData
Join computeOperation In computeOperations On counterData.COUNTER_ID Equals computeOperation.COUNTER_ID
Join counterFormula In countersFormula On counterData.COUNTER_ID Equals counterFormula.COUNTER_ID
Where counterData.COUNTER_DATE >= counterFormula.FROM_DATE And counterData.COUNTER_DATE <= counterFormula.TO_DATE
Select New ComputeOperationData With {.CounterData = counterData, .ComputeOperation = computeOperation, .CounterFormula = counterFormula}
When you see the runtime error message: Unable to cast object of type Generic.List [SomeDerivedType] to Generic.IList[SomeBaseType], you may simply need to Cast the objects to the proper type in the list before making the assignment to the IList.
For example:
Dim objectIList As IList(Of Object)
Dim stringList As New List(Of String)
objectIList = stringList.Cast(Of Object).ToList()
This is tricky because the compiler does not catch this. There are several C# based questions that relate to this issue. Here is one. Here is another.

Unable to cast object of type 'ItemStore.Item' to type 'System.Collections.IEnumerable'

Having a problem displaying the list of items in the view. Can't convert it from a ItemStore.Item to IEnumerable, I've also added ' #Method List(Of ItemStore.Item) ' to list.vbhtml and it can't display The item passed into the dictionary becuase is of type 'Item Store.Item', but this dictionary requires a model item of type 'System.Collections.Generic.List`1[Item Store.Item]'.
****CatalogueController**********
Function About() As ActionResult
Return View()
End Function
Function Index() As String
Return "Index"
End Function
Function List(search As String) As ActionResult
Dim model As New SQLItemModel
Dim items = model.SelectById(search)
Return View(items)
End Function
******List.vbhtml***********
The search text is #ViewBag.Message
#For Each item In Model
#item.ID
*********SQLItemModel.vb***********
Private connectionString As String = My.Settings.sqlconnection
Public Function SelectAll() As ICollection(Of Item)
Dim items As New List(Of Item)
Using connection As New SqlConnection(connectionString)
connection.Open()
Dim cmd As New SqlCommand("select * from item", connection)
Dim reader As SqlDataReader = cmd.ExecuteReader()
While reader.Read()
items.Add(GetItem(reader))
End While
End Using
Return items
End Function
Public Function SelectById(ItemID As Integer) As Item
Dim item As Item = Nothing
Using connection As New SqlConnection(connectionString)
connection.Open()
Dim cmd As New SqlCommand()
cmd.CommandText = "select * from Tbl_Items where ID = #ID"
cmd.Connection = connection
cmd.Parameters.Add(New SqlParameter("ID", ItemID))
Dim reader As IDataReader = cmd.ExecuteReader()
If reader.Read() Then
Item = GetItem(reader)
End If
End Using
Return Item
End Function
Private Function GetItem(reader As SqlDataReader) As Item
Dim ID = reader("ID")
Dim ProductCode = reader("ProductCode")
Dim Brand = reader("Brand")
Dim Description = reader("Description")
Dim Colour = reader("Colour")
Dim Finish = reader("Finish")
Dim Type = reader("Type")
Dim Size = reader("Size")
Dim Unit = reader("Unit")
Return New Item(ID, ProductCode, Brand, Description, Colour, Finish, Type, Size, Unit)
End Function
SelectById just returns a single Item (while SelectAll returns a collection of Items), but your List view expects a collection.
An easy fix would be to just wrap the single item in an array:
Function List(search As String) As ActionResult
Dim model As New SQLItemModel
Dim items = model.SelectById(search)
Return View({items})
End Function

Sorting or Ordering values returned in a EF query MVC 3 vb.net app

I am using a where comparer in the below snippet from my function.. I need to order or sort the returned items by one of the columns... I tried using .OrderBy(function(f) f.regDate) but that dont work at all...
The part of the function in question looks like this:
Function ClassFiller() As ActionResult
Dim _courses As List(Of cours) = db.courses.ToList
Dim _registrants As List(Of reg_info) = db.reg_info.ToList
Dim _classSpec As List(Of classrm) = db.classrms.ToList
Dim _CurrRegistrants As List(Of reg_classes) = db.reg_classes.ToList
For Each Course In _courses.Where(Function(a) a.course_day = "Tuesday")
Dim _CurrCourse As cours = Course
Dim _classRoom As classrm = db.classrms.Where(Function(b) b.Course_ID = _CurrCourse.course_ref).FirstOrDefault()
Dim _classmax As Integer = _classRoom.ClassMax - 1
For Each reg In _registrants.Where(Function(d) d.tues_class1 = _CurrCourse.course_ref).OrderBy(Function(f) f.reg_date)
Dim _ClassCount As Integer = db.reg_classes.Where(Function(c) c.tues_class = _CurrCourse.course_ref).Count
I need to have the _registrants ordered or sorted by a value that is in the db.reg_info under the reg_date column... Any ideas??
Where _registrant is declared at I should have used the following instead:
Dim _registrants As List(Of reg_info) = db.reg_info.OrderBy(Function(t) t.reg_date).ToList
then it will already be ordered.. So the orderby is not needed in the For Each reg In _Registrants.

Combining extension methods

I'm trying to write 2 extension methods to handle Enum types. One to use the description attribute to give some better explanation to the enum options and a second method to list the enum options and their description to use in a selectlist or some kind of collection.
You can read my code up to now here:
<Extension()> _
Public Function ToDescriptionString(ByVal en As System.Enum) As String
Dim type As Type = en.GetType
Dim entries() As String = en.ToString().Split(","c)
Dim description(entries.Length) As String
For i = 0 To entries.Length - 1
Dim fieldInfo = type.GetField(entries(i).Trim())
Dim attributes() = DirectCast(fieldInfo.GetCustomAttributes(GetType(DescriptionAttribute), False), DescriptionAttribute())
description(i) = If(attributes.Length > 0, attributes(0).Description, entries(i).Trim())
Next
Return String.Join(", ", description)
End Function
<Extension()> _
Public Function ToListFirstTry(ByVal en As System.Enum) As IEnumerable
Dim type As Type = en.GetType
Dim items = From item In System.Enum.GetValues(type) _
Select New With {.Value = item, .Text = item.ToDescriptionString}
Return items
End Function
<Extension()> _
Public Function ToListSecondTry(ByVal en As System.Enum) As IEnumerable
Dim list As New Dictionary(Of Integer, String)
Dim enumValues As Array = System.Enum.GetValues(en.GetType)
For Each value In enumValues
list.Add(value, value.ToDescriptionString)
Next
Return list
End Function
So my problem is both extension methods don't work that well together. The methods that converts the enum options to an ienumerable can't use the extension method to get the description.
I found all kind of examples to do one of both but never in combination with each other. What am I doing wrong? I still new to these new .NET 3.5 stuff.
The problem is that Enum.GetValues just returns a weakly typed Array.
Try this:
Public Function ToListFirstTry(ByVal en As System.Enum) As IEnumerable
Dim type As Type = en.GetType
Dim items = From item In System.Enum.GetValues(type).Cast(Of Enum)() _
Select New With {.Value = item, .Text = item.ToDescriptionString}
Return items
End Function
(It looks like explicitly typed range variables in VB queries don't mean the same thing as in C#.)

Resources