Francis
Francis

Reputation: 343

Datagridview returns System.NullReference Exception

This code gives me in a messagebox: "System.NullReferenceException: Object reference not set to an instance to an object" This solution is from another question from me, but doesn`t work. Maybe someone knows, where the mistake hides?

private void button1_Click(object sender, EventArgs e)
        {
            try
            {

                //Setup list object
                var llist = new List<MyClass>();
                //Loop through datagridview rows
                foreach (DataGridViewRow row in dataGridView1.Rows)
                {
                    var obj = new MyClass()
                    {
                        Datum = row.Cells["Datum"].Value.ToString(),
                        Nachricht = row.Cells["Nachricht"].Value.ToString()
                    };
                    llist.Add(obj);
                }
                //Write out JSON file
                string export = JsonConvert.SerializeObject(new { types = llist }, Formatting.Indented);
                File.WriteAllText(@"C:\test\upload" + "\\" + "export.json", export);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }



        }
        public class MyClass
        {
            public string Datum { get; set; }
            public string Nachricht { get; set; }

        }

Upvotes: 0

Views: 106

Answers (1)

sallushan
sallushan

Reputation: 1147

As I have already said in my comments, add null checking before you read the values from cells.

            //Setup list object
            var llist = new List<MyClass>();
            //Loop through datagridview rows
            foreach (DataGridViewRow row in dataGridView1.Rows)
            {
                // ------------------ changed code ----------------------
                string datNum = null;     // by-default we say it will be null
                string nachricht = null;  // same with other field
                // now we will check if cell does NOT have a  null value
                if (row.Cells["Datum"].Value != null)
                    // then we will put it in a variable
                    datNum = row.Cells["Datum"].Value.ToString();
                // similarly for other variable as well
                if (row.Cells["Nachricht"].Value != null)
                    nachricht = row.Cells["Nachricht"].Value.ToString();
                var obj = new MyClass()
                {
                    Datum = datNum,
                    Nachricht = nachricht
                };
                // ------------------------------------------------------
                llist.Add(obj);
            }

Upvotes: 1

Related Questions