Заполнить лист из датагрида - C#
Формулировка задачи:
Пытаюсь заполнить List из DataGridView (в нем лежит список яблок).
Класс яблок:
Код:
Ошибка в строке: "item.ID = int.Parse(dc.Value.ToString());".
Текст ошибки: "Необработанное исключение типа "System.NullReferenceException" - Ссылка на объект не указывает на экземпляр объекта".
public class Apple { public int ID { get; set; } public string name { get; set; } }
List<Apple> apple = new List<Apple>(); foreach (DataGridViewRow dgRow in dataGridView1.Rows) { Apple item = new Apple(); foreach (DataGridViewCell dc in dgRow.Cells) { if (dc.OwningColumn.Index == 0) { item.ID = int.Parse(dc.Value.ToString()); } if (dc.OwningColumn.Index == 1) { item.name = dc.Value.ToString(); } } apple.Add(item); } Console.WriteLine("Список яблок:"); foreach (var app in apple) { Console.WriteLine("№яблока: {0}, яблоко: {1}", app.ID, app.name); }
Решение задачи: «Заполнить лист из датагрида»
textual
Листинг программы
foreach (DataGridViewRow dgRow in dataGridView1.Rows) { Apple item = new Apple(); if (dgRow.Cells[0].Value != null && dgRow.Cells[1].Value != null) { item.ID = int.Parse(dgRow.Cells[0].Value.ToString()); item.name = dgRow.Cells[1].Value.ToString(); apple.Add(item); } }
ИИ поможет Вам:
- решить любую задачу по программированию
- объяснить код
- расставить комментарии в коде
- и т.д