Reputation: 95574
I'm currently trying to get a dataset from SQL server into a list so I can then display this on a page. I've honestly looked at a lot of answers here, and every different attempt brings me to a different error.
From what I've read, this should work. ScriptList
is a List
and should have the Add
functionality. However, it simply doesn't. This is my code at the moment:
public ScriptList Index()
{
var scriptList = new ScriptList();
//List<ScriptItem> scriptlst = new List<ScriptItem>();
string connectionString = _configuration["ConnectionString:localhost"];
using (SqlConnection connection = new SqlConnection(connectionString))
{
string statement = "SELECT ScriptGUID, ScriptName, ScriptDescription, DateAdded FROM dbo.Scropts;";
SqlCommand command = new SqlCommand(statement, connection);
connection.Open();
using (SqlDataReader reader = command.ExecuteReader())
{
while(reader.Read())
{
scriptList.Add<ScriptItem>(new ScriptItem{GUID = Convert.ToString(reader["ScriptGUID"]),
Name = Convert.ToString(reader["ScriptName"]),
ShortDescription = Convert.ToString(reader["ScriptDescription"]),
DateAdded = Convert.ToDateTime(reader["DateAdded"])});
}
}
}
return scriptList;
}
}
public class ScriptList
{
public List<ScriptItem> ScriptItems {get;set;}
}
public class ScriptItem
{
public string GUID {get;set;}
public string Name {get;set;}
public string ShortDescription {get;set;}
public DateTime DateAdded {get;set;}
}
This gives me the error below:
'ScriptList' does not contain a definition for 'Add' and the best extension method overload 'ConfigurationExtensions.Add(IConfigurationBuilder, Action)' requires a receiver of type 'IConfigurationBuilder'
I've tried change the definition of ScriptList
to List<ScriptItem> scriptlist = new List<ScriptItem>();
however, this then results in the error below:
Cannot implicitly convert type 'System.Collections.Generic.List' to 'asp.Pages.ScriptList'
I really don't understand what's wrong here. Why does scriptList
not have the Add
functionality, and why is it that scriptlist
does yet despite that both are declared as List<ScriptItem>
that aren't (apparently) the same?
Upvotes: 1
Views: 373
Reputation: 590
You would want to use scriptlist.ScriptItems.Add()
in your example.
Upvotes: 4
Reputation: 2709
Your list is defined within the ScriptList class, so you need to do:
scriptList.ScriptItems.Add();
Upvotes: 2
Reputation: 151584
No, you have created a class that has a List<T>
member. That doesn't mean that your class inherits all members from said member.
You're simply looking for scriptList.ScriptItems.Add()
, note the added ScriptItems
. That is your list, not your ScriptList
class.
Upvotes: 6