I need to append values to a list of Class Category.
I have tried several combinations including appending 1 row at the time or append a range.
marticle.ListOfCategories.Add(crow); THiS DID NOT WORK
// marticle.ListOfCategories(ccarticle); THiS DID NOT WORK
I get the following error:
Object reference not set to an instance of an object.
Here is my category class:
public class Category
{
public int ID { get; set; }
[Required]
public string Title { get; set; }
}
And here is my view model
public class ArticleEditViewModel
{
public int ID { get; set; }
[Required]
public Boolean Active { get; set; }
[Required]
public string Title { get; set; }
public List<Category> ListOfCategories { get; set; }
}
And here is my recordset append(s) plural
public ArticleEditViewModel ArticleSelectById(int? id)
{
ArticleEditViewModel marticle = new ArticleEditViewModel();
string connString =
System.Configuration.ConfigurationManager.ConnectionStrings["mydb"].ConnectionString;
using (SqlConnection conn = new SqlConnection(connString))
{
conn.Open();
using (SqlCommand cmd = new SqlCommand())
{
cmd.Connection = conn;
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.CommandText = "content.Article_Select_ById";
cmd.Parameters.Add("@ID", SqlDbType.Int).Value = id;
using (SqlDataReader rdr = cmd.ExecuteReader())
{
while (rdr.Read())
{
if (rdr["ID"] != DBNull.Value)
{
marticle.ID = Convert.ToInt32(rdr["ID"]);
}
if (rdr["Title"] != DBNull.Value)
{
marticle.Title = rdr["Title"].ToString();
}
}
}
}
conn.Close();
//Append the list of categories
List<Category> ccarticle = new List<Category>();
conn.Open();
using (SqlCommand cmd = new SqlCommand())
{
cmd.Connection = conn;
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.CommandText = "dbo.Category_SelectAllActive";
using (SqlDataReader rdr = cmd.ExecuteReader())
{
while (rdr.Read())
{
Category crow = new Category();
if (rdr["ID"] != DBNull.Value)
{
crow.ID= Convert.ToInt32(rdr["ID"]);
}
if (rdr["Description"] != DBNull.Value)
{
crow.Description = rdr["Description"].ToString();
}
crow.Active = true;
ccarticle.Add(crow);
marticle.ListOfCategories.Add(crow); //THiS DID NOT WORK
}
}
}
// marticle.ListOfCategories(ccarticle); THiS DID NOT WORK
}
return marticle;
}