0

I am importing excel data to dataGridView from this Link. But I get error "Object reference not set to an instance of an object".

        String name = "Sheet1";
        String constr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" +
                        file +
                        ";Extended Properties='Excel 8.0;HDR=YES;';";

        OleDbConnection con = new OleDbConnection(constr);
        OleDbCommand oconn = new OleDbCommand("Select * From [" + name + "$]", con);
        con.Open();

        OleDbDataAdapter sda = new OleDbDataAdapter(oconn);
        System.Data.DataTable data = new System.Data.DataTable();
        sda.Fill(data);
        dgvIM.DataSource = data;
Tasneem
  • 167
  • 2
  • 10
  • Possible duplicate of [What is a NullReferenceException, and how do I fix it?](https://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – rene Jul 04 '17 at 12:47
  • 1
    On which line do you get that exception? – rene Jul 04 '17 at 12:47
  • On the last line dgvIM.DataSource = data; – Tasneem Jul 04 '17 at 12:53
  • Can you show the rest of the code? Or at least where you are calling this from. – Tamás Szabó Jul 04 '17 at 13:01
  • Here I call it: private void toolStripMenuItem3_Click(object sender, EventArgs e) { Import(); } – Tasneem Jul 04 '17 at 13:04
  • I have no idea how you managed to set your `DataGridView` to null... if you click on `dgvIM` and press F12 (or right click -> Go to definition) where does it take you? To a `designer.cs` file? Can you show that code snippet? – Tamás Szabó Jul 04 '17 at 13:29
  • it takes me to its definition: DataGridView dgvIM; – Tasneem Jul 04 '17 at 13:47

1 Answers1

0

Check the value of dgvIM when debugging. It's probably null;

LtObelix
  • 36
  • 3