so like my question said, I doing a mySQL query but the query is giving me some headache as I am trying to retrieve the data from my database as a object so I can reiterate in my javascript code however the data I retrieve out from the database is all null and 0 despite my database it self do not have value with null or 0. I have set my database value that it cannot be null.
So, this is the value in my database:
This is the data that I retrieved till.
{"Musicid":0,"Audioid":null,"Description":null,"MusicTitle":null,"AudioPath":null,"ImagePath":null,"PriceType":null,"UploadDate":"\/Date(-62135596800000)\/","Views":0,"Likes":0,"NoOfReports":0,"Type":null}
This is my C# class
public class music{
public int Musicid { get; set; }
public String Audioid { get; set; }
public String Description { get; set; }
public String MusicTitle { get; set; }
public String AudioPath { get; set; }
public String ImagePath { get; set; }
public String PriceType { get; set; }
public DateTime UploadDate { get; set; }
public int Views { get; set; }
public int Likes { get; set; }
public int NoOfReports { get; set; }
public String Type { get; set; }
public music(int musicid, String audioid, String description, String MusicTitle, String audioPath, String imagePath, String priceType, DateTime uploadDate, int views, int likes, int noOfreports, String Type)
{
musicid = this.Musicid;
audioid = this.Audioid;
description = this.Description;
MusicTitle = this.MusicTitle;
audioPath = this.AudioPath;
imagePath = this.ImagePath;
priceType = this.PriceType;
uploadDate = this.UploadDate;
views = this.Views;
likes = this.Likes;
noOfreports = this.NoOfReports;
Type = this.Type;
}
}
This is my c# code
public List<music> Searchdatabase(String searchvalue)
{
List<music> al = new List<music>();
ArrayList array = new ArrayList();
//sql connection, query values to database error need help
string cs = ConfigurationManager.ConnectionStrings["test"].ConnectionString;
using (MySqlConnection con = new MySqlConnection(cs))
{
con.Open();
String query = "SELECT music.* FROM music WHERE MusicTitle LIKE #search";
MySqlCommand command = new MySqlCommand(query, con);
command.Parameters.AddWithValue("#search", "%" + searchvalue + "%");
using (MySqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
if (searchvalue == null || searchvalue == "")
{
break;
}
else
{
al.Add(new music(reader.GetInt32(0), reader.GetString(1), reader.GetString(2), reader.GetString(3), reader.GetString(4), reader.GetString(5), reader.GetString(6), reader.GetDateTime(7), reader.GetInt32(8), reader.GetInt32(9) , reader.GetInt32(10), reader.GetString(11)));
}
}
if (reader != null)
reader.Close();
}
}
return al;
}
The command seems to be working just like whatever I key to the searchbox value which is for searchvalue like anything that not related to the musicTitle in the database will provided me with nothing which is correct. But anything that have relation to the musicTitle it return me the object array just that the value retrieved is null and 0 despite having data in database.
I know this may be lengthy, hopefully someone can help me. Thanks
Your constructor code is wrong. You're assigning values to constructor parameters rather than the other way around.
public music(int musicid, String audioid, String description, String MusicTitle, String audioPath, String imagePath, String priceType, DateTime uploadDate, int views, int likes, int noOfreports, String Type)
{
this.Musicid = musicid;
....
this.NoOfReports = noOfreports;
this.Type = Type;
}
Also, look into object initializers instead, so you don't write these ridiculous constructors.
new music { Musicid = musicid, Type, NoOfReports = noOfreports .... };
In this case you don't even need a constructor. As you can see, if the variable name is the same as the property name, you don't have to write this as X = Y, but just X. So it's like a constructor, but you don't have to write the actual constructor.
Your constructor has everything in reverse order. You are setting the arguments instead of the properties. Change it to this and try again.
public music(int musicid, String audioid, String description, String MusicTitle, String audioPath, String imagePath, String priceType, DateTime uploadDate, int views, int likes, int noOfreports, String Type)
{
this.Musicid =musicid;
this.Audioid = audioid;
this.Description = description;
this.MusicTitle = MusicTitle;
this.AudioPath = audioPath;
this.ImagePath = imagePath;
this.PriceType = priceType;
this.UploadDate = uploadDate;
this.Views = views;
this.Likes = likes;
this.NoOfReports = noOfreports;
this.Type = Type;
}
Related
I am doing a project. This project involves a database with a table called 'Customers'. In the same project, I have a form called 'frmAddNewCustomer'. This form takes in 9 attributes relating to the customer. There is a button that when clicked has code that allows these attributes to be entered into the database respectively. I also have a class called 'CustomerDAL' that allows me to performs tasks on the database table (Insert, Update, Delete etc.) and class holds the method that I used to enter data into the database from the 'frmAddNewCustomer' form. Finally, I have a Class called 'CustomerModel' which represents a record in the database. In the CustomerDAL class, the parameters for the method mentioned earlier (the one that allows me to enter data to the database through the UI form) are an object created from the CustomerModel class. my problem is that in the UI form it says that the method has no overload for 9 arguements.
this is the customer model class:
public int CustomerID { get; set; }
public string Title { get; set; }
public string Forename { get; set; }
public string Surname { get; set; }
public string Email { get; set; }
public string Streetname { get; set; }
public string Town { get; set; }
public string County { get; set; }
public string Postcode { get; set; }
public string WeddingGiftList { get; set; }
public CustomerModel( string title, string forename, string surname, string email, string streetname,string town, string county, string postcode, string weddingGiftlist)
{
Title = title;
Forename = forename;
Surname = surname;
Email = email;
Streetname = streetname;
Town = town;
County = county;
Postcode = postcode;
WeddingGiftList = weddingGiftlist;
}
public CustomerModel()
{
}
this is the CustomerDAL class:
private static string _connectionString = ConfigurationManager.ConnectionStrings["SimpsonsConnection"].ConnectionString;
public static int AddNewCustomer(CustomerModel newCustomer)
{
using (SqlConnection connection = new SqlConnection(_connectionString))
{
connection.Open();
string sqlQuery = string.Format("INSERT INTO [Customer] VALUES('{0}', '{1}', '{2}', '{3}', '{4}', '{5}','{6}','{7}','{8}')", newCustomer.Title, newCustomer.Forename, newCustomer.Surname, newCustomer.Email, newCustomer.Streetname, newCustomer.Town, newCustomer.County, newCustomer.Postcode, newCustomer.WeddingGiftList);
SqlCommand insertCommand = new SqlCommand(sqlQuery, connection);
int rowsAffected = insertCommand.ExecuteNonQuery();
connection.Close();
return rowsAffected;
}
}
//this is the UI forms click event on the button:
//this is to add the customer details to the database when the 'Create button is clicked'
if ( cmbxTitle.Text != "" || txtForename.Text != "" || txtSurname.Text != "" || txtEmail.Text != "" || txtStreetName.Text != "" || txtTown.Text != "" || txtCounty.Text != "" || txtPostCode.Text != "" || cmbxWeddingGiftList.Text != "")
{
int rowsAffected = CustomerDAL.AddNewCustomer(cmbxTitle.Text, txtForename.Text, txtSurname.Text, txtEmail.Text, txtStreetName.Text, txtTown.Text, txtCounty.Text, txtPostCode.Text, cmbxWeddingGiftList.Text);
if(rowsAffected == 1)
{
MessageBox.Show("Customer has been added successfully");
Form myNextScreen = new frmMenu();
myNextScreen.Show();
}
else
{
MessageBox.Show("Customer was not able to be registered. Please re-enter details carefully");
}
}
else
{
lblInfo.Visible = true;
MessageBox.Show("Please enter all details");
}
In the UI form my error is when I reference the 'AddNewCustomer' method from the CustomerDAL class.error Image
I'm just not sure how to fix this error as I think I have 9 arguments?
It would mean a lot if you could help me with this as I'm relatively new to databases in c#
In my opinion, your problem can be in not defining the object
int rowsAffected = CustomerDAL.AddNewCustomer(new CustomerModel{....});
instead of this
int rowsAffected = CustomerDAL.AddNewCustomer(cmbxTitle.Text, txtForename.Text, txtSurname.Text, txtEmail.Text, txtStreetName.Text, txtTown.Text, txtCounty.Text, txtPostCode.Text, cmbxWeddingGiftList.Text);
have this
var newCustomer = new Customer
{
Title = cmbxTitle.Text,
//rest of customer properties
};
int rowsAffected = CustomerDAL.AddNewCustomer(newCustomer)
I'm getting data from a remote Database, so I don't actually know the column types I'm dealing with. So I was using dataReader.GetString(X) as a default. I can save those values into variables, but when actually trying to send the variables into an object constructor it fails (before getting inside the constructor) with an error : System.FormatException: Input string was not in a correct format. If I can save them to string type variables why does it give an error when trying to use those variables to create an object and not before?
//VARIABLES
DateTime PreparationDate;
string ClientId;
string ClientName;
string BL;
string QTD_TOT;
string QTD_PREP;
string X_QTD;
string TAXA;
string query = GetPreparationsMACPAC;
SqlConnection con = new SqlConnection(_connectionString);
if (con.State == ConnectionState.Closed) con.Open();
SqlCommand cmd = new SqlCommand(query, con);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataReader dr = cmd.ExecuteReader();
List<PreparationViewModel> shippingsList = new List<PreparationViewModel>();
PreparationViewModel prep = new PreparationViewModel(new DateTime(), "1", "2", "3", "4", "5", "6", "7");
if (dr.HasRows)
{
while (dr.Read())
{
PreparationDate = dr.GetDateTime(0);
ClientId = dr.GetString(1);
ClientName = dr.GetString(2);
BL = dr.GetString(3);
QTD_TOT = dr.GetString(4);
QTD_PREP = dr.GetString(5);
X_QTD = dr.GetString(6);
TAXA = dr.GetString(7);
//THE FOLLOWING OUTPUT IS CORRET (see below)
Console.WriteLine("{0},{1},{2},{3},{4},{5},{6},{7}", PreparationDate, ClientId, ClientName, BL, QTD_TOT, QTD_PREP, X_QTD, TAXA);
//FAILS HERE
try
{
prep = new PreparationViewModel(PreparationDate, ClientId, ClientName, BL, QTD_TOT, QTD_PREP, X_QTD, TAXA);
}
catch (Exception e)
{
Console.WriteLine(e);
}
shippingsList.Add(prep);
}
}
OUTPUT(1Datetime + 7Strings Seperated by ",")
09/04/2021 00:00:00,92843160002,RENAULT MONTAJE VALLADOLID,506653,120,120,0.000,1.0000000
CLASS MODEL
public class PreparationViewModel
{
public PreparationViewModel()
{
}
public PreparationViewModel(DateTime preparationDate, string clientId, string clientName, string transportDocumentId,
string totalQuantity, string preparedQuantity, string xQuantity, string complianceRate)
{
//BREAKPOINT IS SET, NOT REACHED FROM THE TRY/CATCH CODE
PreparationDate = preparationDate;
ClientId = clientId;
ClientName = clientName;
TransportDocumentId = transportDocumentId;
TotalQuantity = Int16.Parse(totalQuantity);
PreparedQuantity = Int16.Parse(preparedQuantity);
XQuantity = float.Parse(xQuantity);
ComplianceRate = float.Parse(complianceRate);
}
public DateTime PreparationDate {get;set;}
public string ClientId { get; set; }
public string ClientName { get; set; }
public string TransportDocumentId { get; set; }
public int TotalQuantity { get; set; }
public int PreparedQuantity { get; set; }
public float XQuantity { get; set; }
public float ComplianceRate { get; set; }
}
I'm getting data from a remote database so I donĀ“t know exactly the column types
In that scenario, your best bet is probably something like:
short prepQty = Convert.ToInt16(reader.GetValue(5), CultureInfo.InvariantCulture);
(or if you don't want the invariant culture: replace with whatever culture you do want; if the values are strings and you don't know the culture: you've already lost the battle)
This will handle more data types and have better defined semantics when handling strings. It would be advisable to keep the read/parse code in the code that handles the reader, and have the PreparationViewModel just take the parsed value (the short).
I am very new to C#. I am writing a program using visual studio c# where it will first ask the user to enter an employee name. Next, it will pass that name through an API and will retrieve and display the employee signature. I have completed this portion.
Next, the program will ask the user to enter a designated "to" and "from" date. Next, the program should pass the date information as well as the signature obtained previously through a second API and retrieve and display information on to a grid data table accordingly.
For the Grid view data table, I understand that I should be connected to a SQL data server, which I am.
My problem is that
I am not sure how to write a code which will pass three parameters to an API (the "to" and "from" date, and the employee signature). I have tried the code below, however, I receive an error when I try to link the corresponding button to the JSON code to retrieve data. The error states that
"There is no argument given that corresponds to the required formal
parameter 'toDate' of 'WebAPI.GetTime(double, double, string).'
I am not sure how to pass the signature previously obtained from a different API through the new API.
Any help would be much appreciated.
Code for defining the JSON variables:
namespace TimeSheet_Try11_Models
{
// Root myDeserializedClass = JsonConvert.DeserializeObject<Root>(myJsonResponse);
public class OracleHour
{
public string orderNumber { get; set; }
public DateTime dateOfWork { get; set; }
public string description { get; set; }
public string surveyor { get; set; }
public string hourType { get; set; }
public double hours { get; set; }
public int status { get; set; }
public string savedInOlsonTimezone { get; set; }
public double invoicelinevalue { get; set; }
public string articleType { get; set; }
public DateTime dateOfWorkInSavedTimezone { get; set; }
}
public class MyArray
{
public string orderNumber { get; set; }
public string projectnumber { get; set; }
public string noteToInvoicer { get; set; }
public List<object> oracleCosts { get; set; }
public List<OracleHour> oracleHours { get; set; }
}
public class Root1
{
public List<MyArray> MyArray { get; set; }
}
}
Code calling out the JSON:
namespace TimeSheets_Try_11.Controllers
{
class WebAPI
{
public string[] GetTime(double fromDate, double toDate, string username)
{
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
var cookies = FullWebBrowserCookie.GetCookieInternal(new Uri(StaticStrings.UrlNcert), false);
WebClient wc = new WebClient();
wc.Encoding = System.Text.Encoding.UTF8;
wc.Headers.Add("Cookie:" + cookies);
wc.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
wc.UseDefaultCredentials = true;
string url = "";
url = $"{StaticStrings.UrlNcert}?user={username}&fromDate={fromDate:yyyy-MM-dd}&toDate={toDate:yyyy-MM-dd}";
var respons = wc.DownloadString(url);
OracleHour ndata = JsonConvert.DeserializeObject<OracleHour>(respons);
var Get_Odnum = ndata.orderNumber;
var Dt_Work = ndata.dateOfWork;
var hrType = ndata.hourType;
var hr = ndata.hours;
var des = ndata.description;
var surname = ndata.surveyor;
string[] myncertdata = { Get_Odnum, Dt_Work.ToString(), hrType, hr.ToString(), des, surname };
return myncertdata;
}
}
Partial code attempting to connect the corresponding button to retrieve data (the error appears at the very last line):
namespace TimeSheets_Try_11
{
public partial class Form3 : Form
{
WebAPI WA = new WebAPI();
public Form3()
{
InitializeComponent();
webBrowser2.Url = new Uri(StaticStrings.UrlNcert);
}
private void Form3_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'timesDataSet.NCert_Data' table. You can move, or remove it, as needed.
this.nCert_DataTableAdapter.Fill(this.timesDataSet.NCert_Data);
}
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
}
private void GtData_Click(object sender, EventArgs e)
{
var connetionString = ConfigurationManager.ConnectionStrings["Times"].ConnectionString;
try
{
using (SqlConnection conn = new SqlConnection(connetionString))
{
using (SqlCommand cmd = new SqlCommand())
{
conn.Open();
using (SqlCommand Sqlcmd = new SqlCommand("NCert_Data", conn))
{
Sqlcmd.CommandType = CommandType.StoredProcedure;
int counter; string projectnumber; double hrs; string respname; string describe; string[] prjstat; DateTime dates;
for (counter = 0; counter < (dataGridView1.RowCount) - 1; counter++)
{
hrs = 0;
projectnumber = dataGridView1.Rows[counter].Cells[1].Value.ToString();
prjstat = WA.GetTime(projectnumber);
}
}
}
}
}
}
}
public string[] GetTime(double fromDate, double toDate, string username)
needs 3 parameter but
prjstat = WA.GetTime(projectnumber);
has only one...?
Looks like you have to add 2 more parameters
prjstat = WA.GetTime((double), (double), "text");
double fromDate, but you have "projectnumber" a .toString() ...?
Without knowing how the structure of your table looks like there is no way to know what the parameters are. How ever I think your function call should look like this:
prjstat = WA.GetTime((double)dataGridView1.Rows[counter].Cells["fromDate"], (double)(double)dataGridView1.Rows[counter].Cells["toDate"], dataGridView1.Rows[counter].Cells["username"].toString());
Where ["fromDate"], ["toDate"] and ["username"] should be the correct indexes of your expected data.
You may could loop through the cols and output the data with something like that:
for (counter = 0; counter < (dataGridView1.RowCount) - 1; counter++)
{
for (int i = 0; i < dataGridView1.Columns.Count, i++)
{
if (dataGridView1.Columns[i].HeaderText != null) {
System.Console.WriteLine(dataGridView1.Columns[i].HeaderText);
}
System.Console.WriteLine(dataGridView1.Rows[counter].Columns[i].ValueType.ToString());
System.Console.WriteLine(dataGridView1.Rows[counter].Columns[i].Value.ToString());
}
if (counter == 2) { break; }
}
Or just give some dummy values and look what happens ( :P ):
prjstat = WA.GetTime(0, 0, "bla");
Edit: Please note that .Value can be different types like numbers colors dates or what ever. So you have to cast it to a type (double) or use Convert.XYZ. By ValueType.toString() you maybe know what type it is. Or you already know it at all, no idea... ;)
...should pass the date information as well as the signature obtained previously through a second API and retrieve and display information on to a grid data table accordingly.
Well now I'm confused. Could you clarify if you want to store data received by WA.GetTime to dataGridView1 or do you want to send data to WA.GetTime obtained by the dataGridView1?
Btw.: A DataGridView do not "require" an sql database. It can also use xml as example.
I am new to programming so i don't know what i am doing.
I am pulling enum value from different class and set them as getter and setter.
namespace DataLayer.Entities
{
public enum CourseModeOfDelivery
{
Online, ClassRoom, ELearning,
}
public class Course
{
public int ID { get; set; }
public String CourseName { get; set; }
public String Description { get; set; }
public DateTime StartDate { get; set; }
public DateTime EndDate { get; set; }
public CourseModeOfDelivery CourseMode { get; set; }
}
reading this value in courseRepository
public static Course GetCourse(int id)
{
Course a = new Course();
String GetCommand = "Select CourseName, Description, StartDate, EndDate, CourseMode from Course" + "Where ID = #CourseID";
SqlConnection connection = DBManager.GetSqlConnection();
SqlCommand command = new SqlCommand(GetCommand, connection);
command.Parameters.AddWithValue("#StudentID", id);
try
{
var reader = command.ExecuteReader();
//Read the Command Object and then return details
if (reader.HasRows)
{
while (reader.Read())
{
a.ID = Convert.ToInt32(reader["ID"]);
a.CourseName = reader["CourseName"].ToString();
a.Description = reader["Description"].ToString();
a.StartDate = DateTime.Parse(reader["StartDate"].ToString());
a.EndDate = DateTime.Parse(reader["EndDate"].ToString());
var selection = CourseModeOfDelivery.ClassRoom;
switch (selection)
{
case CourseModeOfDelivery.ClassRoom:
a.CourseMode = CourseModeOfDelivery.ClassRoom;
return a.CourseMode;
case CourseModeOfDelivery.ELearning:
a.CourseMode = CourseModeOfDelivery.ELearning;
return a.CourseMode;
case CourseModeOfDelivery.Online:
a.CourseMode = CourseModeOfDelivery.Online;
return a.CourseMode;
}
a.CourseMode =
}
}
else
{
reader.Close();
}
}
The requirement is to use switch but don't know how to pull data in there.
It depends on the type of database field you use.
If it is int then:
a.CourseMode = (CourseModeOfDelivery) reader["CourseMode"];
If it is String then:
a.CourseMode = (CourseModeOfDelivery) Enum.Parse(typeof(CourseModeOfDelivery), reader["CourseMode"].toString());
The following might also help you:
https://msdn.microsoft.com/en-us/library/essfb559(v=vs.110).aspx
Cast int to enum in C#
I am trying to extend a class to another class that will collect them as a list.
model:
public class Brand
{
public int BrandId { get; set; }
public string Name { get; set; }
public string Guid { get; set; }
public float Rating { get; set; }
public string Industry { get; set; }
public string Address1 { get; set; }
public string Address2 { get; set; }
public string City { get; set; }
public string State { get; set; }
public string Postal { get; set; }
public string CountryCode { get; set; }
public virtual Snapshot Snapshot { get; set; }
}
public class Snapshot
{
public int ID { get; set; }
public string Guid { get; set; }
public int CompanyID { get; set; }
public string CompanyName { get; set; }
public string Email { get; set; }
public DateTime DateTimeSent { get; set; }
public string Subject { get; set; }
public string Html { get; set; }
public string Image { get; set; }
public string Unsubscribe { get; set; }
}
public class BrandSnaphotViewModel
{
public Brand Brand { get; set; }
public List<Snapshot> SnapshotItems { get; set; }
}
controller:
public ActionResult Index(string brandGuid)
{
BrandSnaphotViewModel viewModel = new BrandSnaphotViewModel();
Brand brand = GetBrand(brandGuid);
viewModel.Brand = brand;
List<Snapshot> snapshot = GetBrandSnapshots(brand.BrandId);
viewModel.SnapshotItems = snapshot;
List<BrandSnaphotViewModel> viewModelList = new List<BrandSnaphotViewModel>();
viewModelList.Add(viewModel);
return View(viewModelList.AsEnumerable());
}
private Brand GetBrand(string brandGuid)
{
Brand brand = new Brand();
string dbConnString = WebConfigurationManager.ConnectionStrings["dbConn"].ConnectionString;
MySqlConnection dbConn = new MySqlConnection(dbConnString);
dbConn.Open();
MySqlCommand dbCmd = new MySqlCommand();
dbCmd.CommandText = "SELECT *, industries.name AS industry_name FROM brands LEFT JOIN industries ON brands.industry_id = industries.industry_id WHERE brand_guid = '" + brandGuid.ToString() + "' AND private = 0 LIMIT 1";
dbCmd.Connection = dbConn;
MySqlDataReader dbResult = dbCmd.ExecuteReader();
if (dbResult.Read())
{
brand.Guid = dbResult["brand_guid"].ToString();
brand.BrandId = Convert.ToInt32(dbResult["brand_id"]);
brand.Industry = dbResult["industry_name"].ToString();
}
dbResult.Close();
dbConn.Close();
return brand;
}
private List<Snapshot> GetBrandSnapshots(int brandId)
{
string dbConnString = WebConfigurationManager.ConnectionStrings["dbConn"].ConnectionString;
MySqlConnection dbConn = new MySqlConnection(dbConnString);
dbConn.Open();
MySqlCommand dbCmd = new MySqlCommand();
dbCmd.CommandText = "SELECT * FROM snapshots WHERE brand_id = " + brandId + " AND archive = 0 ORDER BY date_sent DESC";
dbCmd.Connection = dbConn;
MySqlDataReader dbResult = dbCmd.ExecuteReader();
List<Snapshot> snapshots = new List<Snapshot>();
while (dbResult.Read())
{
snapshots.Add(new Snapshot
{
SnapshotId = Convert.ToInt32(dbResult["snapshot_id"]),
Subject = dbResult["subject"].ToString(),
DateTimeSent = Convert.ToDateTime(dbResult["date_sent"]),
Image = dbResult["image"].ToString(),
Email = dbResult["email"].ToString(),
ContentType = dbResult["content_type"].ToString(),
Type = dbResult["type"].ToString()
});
}
dbResult.Close();
dbConn.Close();
return snapshots;
}
edit
FIXED
The issue was the VIEW was not referencing the ViewModel as an IENumerable<>. FACEPALM.
#model IEnumerable<projectvia.ViewModels.BrandSnaphotViewModel>
#{
ViewBag.Title = "Index";
}
#foreach(var item in Model)
{
#item.Brand.Guid;
for(int i = 0; i< #item.SnapshotItems.Count; i++)
{
#item.SnapshotItems[i].Subject<br/>
}
}
That resolved the issue.
Thank you both experts for the insights... i took both advice and came to this solution.
you are doing wrong, it is a list.
you cannot add element this way. Create object and add that object in list by calling Add()
do like this to add items in it:
List<BrandEmailList> brandSnapshotsList = new List<BrandEmailList>();
while (dbResult.Read())
{
BrandEmailList brandSnapshots = new BrandEmailList (); // create an object
brandSnapshots.ID = Convert.ToInt32(dbResult["snapshot_id"]);
brandSnapshots.Guid = dbResult["snapshot_guid"].ToString();
brandSnapshots.DateTimeSent = dbResult["date_sent"];
brandSnapshots.Subject = dbResult["subject"].ToString();
brandSnapshots.Image = dbResult["image"];
brandSnapshotsList.Add(brandSnapshots); // add it in list
}
EDIT:
List is a generic thing, you don't need to create a class for it. you can just instantiate a list and add items in it.
why are you doing like that you can do it this way simply:
List<Snapshot> brandSnapshotsList = new List<Snapshot>();
while (dbResult.Read())
{
Snapshot brandSnapshots = new Snapshot(); // create an object
brandSnapshots.ID = Convert.ToInt32(dbResult["snapshot_id"]);
brandSnapshots.Guid = dbResult["snapshot_guid"].ToString();
brandSnapshots.DateTimeSent = dbResult["date_sent"];
brandSnapshots.Subject = dbResult["subject"].ToString();
brandSnapshots.Image = dbResult["image"];
brandSnapshotsList.Add(brandSnapshots); // add it in list
}
Building on what Ehsan Sajjad did, looking at public IEnumerator<Snapshot> BrandEmails, i believe what you look for looks more like this:
public class Snapshot
{
public int ID { get; set; }
public string Guid { get; set; }
// ...
}
public class BrandEmailList : List<Snapshot>
{
}
You need not even create a new type for your brand email list, you can use List<Snapshot> directly.
public ViewResult Whatever() {
var brand = GetBrand(brandName);
var brandSnapshots = GetBrandSnapshots();
return View(brand, brandSnapshots);
}
private Brand GetBrand(string brandName)
{
try
{
var brand = new Brand();
brand.Name = brandName;
// database stuffs ...
return brand;
}
catch (Exception ex)
{
throw ex;
}
}
private List<Snapshot> GetBrandSnapshots()
{
// ...
// DB stuffs -- that *really* should not be in the controller anyways.
// ...
var snapshots = new List<BrandEmailList>();
while (dbResult.Read())
{
// object initializer syntax
snapshots.Add(new Snapshot {
ID = Convert.ToInt32(dbResult["snapshot_id"]),
Guid = dbResult["snapshot_guid"].ToString(),
DateTimeSent = dbResult["date_sent"],
Subject = dbResult["subject"].ToString(),
Image = dbResult["image"],
});
}
return snapshots
}
As a side note, mixing database access into controller methods can be a bad idea. It does not have to be, but it can be. Generally, fetching data from the database happens at a different "level" than serving a MVC result. MVC controller don't have the "purpose" to talk to a database, that work can/should be delegated to a dedicated type. Compare the single responsibility principle part of the SOLID principles.