Actually, there are 2 grids, one is filled with a collection, the data in the collection is the data from the database.

Method of filling the collection

public List<Food> GetFoods() { List<Food> Foods = new List<Food>(); string query = "select * from Food"; MySqlConnection sqlcon = new MySqlConnection(ConnectionString); MySqlCommand cmd = new MySqlCommand(query, sqlcon); cmd.CommandType = System.Data.CommandType.Text; sqlcon.Open(); MySqlDataReader sqlreader = cmd.ExecuteReader(); object[] row; while (sqlreader.Read()) { row = new object[sqlreader.FieldCount]; sqlreader.GetValues(row); Foods.Add(new Food() { Name = row[0].ToString(), Belki = (decimal)row[1], Jiri = (decimal)row[2], Uglevodi = (decimal)row[3], Ccal = (decimal)row[4], Voda = (decimal)row[5], FoodID = (int)row[6], }); } sqlreader.Close(); return Foods; } 

Filling the grid from the collection

  FoodProvider p = new FoodProvider(); List<Food> food = p.GetFoods(); GridOne.ItemsSource = food; 

During the work of the program, records are added or deleted to the second grid (the second List<Food> collection). I need to click on the button, the content of the second collection was added to the database. Tell me, please, how to insert a collection.

  • one
    First, what does InvalidCastException mean? If you catch him somewhere, where and how? Secondly, what does the first grid mean, if you are interested in adding data from the second one in the question? Thirdly, what exactly does not work when adding data to the database? - DreamChild
  • I apologize for the title, this is my first question in stackflowflow, I used to want to ask another question, but I found a solution to the problem, now this question has appeared, and the title is left from the past of a non-posted question. Can I edit the headline? The first grid here at that. That each grid is filled with its collection. The essence of the question is how to add each element of the collection in the database, I do not know how to do it. - edhar.rybak
  • so what if each grid is filled with its collection? What is the first grid? Foggy explain. Plus, you did not answer the third question - what exactly does not work when adding data to the database? Also, what is your grid? - DreamChild
  • If you have another question - ask it a separate question. - PashaPash
  • Yes, it's not in the grid, he has nothing to do with it, I just do not know how to express myself, Sorry again. The thing is that I do not know how to add each element of the collection in the database. It does not work because I do not know: ( - edhar.rybak

2 answers 2

As an option, make a cyclic enumeration of the elements of the collection and insert each element into the database. Or try to associate the collection with a dataset and use it.

    In order to bring the entire collection into the database, you need to cycle through all the elements of the collection in the foreach loop and add each element to the database, thanks @AlexKrass