Question Populate DataGridView from List -> DataGridView is null

PresFox

New member
Joined
Nov 2, 2021
Messages
1
Programming Experience
Beginner
Hello,

I am reading a CSV file and putting the contents in a list, then trying to use that list as a DataSource for DataGridView:

C#:
public Form1()
        {
            List<string> cityList = File.ReadAllLines("cities.csv").ToList();
            List<UrlList> toDoList = new List<UrlList>();
            toDoList = File.ReadAllLines("todo.csv").Select(v => UrlList.FromCsv(v)).ToList();

            var toDoListData = toDoList.Select(x => new {
                Url = x.url,
                City = x.city,
                Done = x.done



            }).ToList();

            //UpdateList(toDoList);
           
            statusView.DataSource = toDoListData;

            InitializeComponent();
        }

C#:
public class UrlList
    {
        public string url;
        public string city;
        public string done;

        public static UrlList FromCsv(string csvline)
        {
            string[] values = csvline.Split(',');
            UrlList urlList = new UrlList();
            urlList.url = values[0];
            urlList.city = values[1];
            urlList.done = values[2];
            return urlList;
        }
    }

However, I am getting the error that statusView is null. Any help would be appreciated.
 
InitializeComponent is what create, initialize and add the controls to form.
 
You really ought to be doing that work in the Load event handler rather than in the constructor anyway. Constructors shouldn't throw exceptions if at all possible, so doing things like reading files is generally a no go. The constructor should successfully build the form and that's basically what happens in InitializeComponent. If you need to do extra work to construct the form, do it after that call. Loading data and the like should generally be done after the form has successfully been created.
 
Back
Top Bottom