M_Magz M_Magz - 1 year ago 151
C# Question

Visual Studio C# datagridview to database

I'm trying to save data from datagridview to database. I keep on getting a

NullReferenceException: Object reference not set to an instance of an object

foreach (DataGridViewRow row in dataGridView2.Rows)
using ( conn = new SqlConnection(constring))
using (SqlCommand cmd = new SqlCommand("INSERT INTO tbl_Students_Marks VALUES(@Student, @T1, @T2, @T3, @T4)", conn))
cmd.Parameters.AddWithValue("@Student", (row.Cells["Student Number"].Value).ToString());
cmd.Parameters.AddWithValue("@T1", row.Cells["Test 1"].Value);
cmd.Parameters.AddWithValue("@T2", row.Cells["Test 2"].Value);
cmd.Parameters.AddWithValue("@T3", row.Cells["Test 3"].Value);
cmd.Parameters.AddWithValue("@T4", row.Cells["Test 4"].Value);

Answer Source

Looks like your row value is empty.

Try to replace your line 9 with this code:

            var studentNumber = row.Cells["Student Number"].Value
            if (studentNumber == null || studentNumber is DBNull)
            cmd.Parameters.AddWithValue("@Student", studentNumber.ToString());