0

How can I fill products class below with products queried from SQL Server?

public class products
{
    public item[] item { get; set; }
}

public class item
{
    public string id { get; set; }
    public string name { get; set; }
    public string price { get; set; }
}

What I am trying to achieve is a variable with type products that contain a set of products.

products productset = new products();

I am hoping to work with the variable as follow:

lableName.Text = productset.item[4].name;

Please let me know how to fill such a variable with data from SQL.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Rick
  • 33
  • 1
  • 3

1 Answers1

1

To create a set of products you need to create a list. So your products variable will look like this:

List<products> products = new List<products>();

If you want a list of items inside the product object, then you can leave it like this.

I don't exactly know what you mean with 'fill such a variable with data from SQL'. Do you already have the code to query the database, or is that the part that you don't understand/need? Please provide some more info so we can help you out. In case you have code, please post it here.

Frank Levering
  • 401
  • 3
  • 16
  • So if I created this list you mentioned. How do I fell it or assign data from an SQL data reader. I am not able to construct the command inside the while(reader.read()). For example, is it going to be like this: products.Name = reader["name"].ToString(); – Rick Mar 10 '16 at 02:32
  • Microsoft has a lot of documentation on how to do this. For example, here's documentation on how to query results using a DataReader https://msdn.microsoft.com/en-us/library/haa3afyz(v=vs.110).aspx. Also, you can refer to this Stackoverflow question, where they have some example code on how to read from the DataReader: http://stackoverflow.com/questions/4018114/read-data-from-sqldatareader. For creating the command you need to use the SqlCommand object, as explained in the documentation. – Frank Levering Mar 10 '16 at 07:27