Hi guys how do I sort out this error = "object reference not set to an instance of an object"

try
            {

                String connection = "Data Source=(LocalDB)\\v11.0;AttachDbFilename=C:\\Users....";
                SqlConnection conn = new SqlConnection(connection);
                SqlCommand db = new SqlCommand("select * from Tbl", conn);
                SqlCommandBuilder builder = new SqlCommandBuilder(da);
                ds = new DataSet();
                da.Fill(ds, "Tbl");
                dataGridView1.DataSource = ds.Tables["Tbl"];

            } 
            catch (Exception ex)
            {
MessageBox.Show(ex.Message);
}

Hi thank you for your time.
The line that triggers th exception is line 9. "da.Fill(ds, "Tbl");"
and "da" is variable of

SqlDataAdapter da;

You need to create an instance of it with the "new" keyword. SqlDataAdapter da = new SqlDataAdapter(); which should get rid of your error.

Try the following:

String connection = "Data Source=(LocalDB)\\v11.0;AttachDbFilename=C:\\Users...."; SqlConnection conn = new SqlConnection(connection); 
SqlDataAdapter da = new SqlDataAdapter("select * from Tbl", conn); 
ds = new DataSet(); 
da.Fill(ds, "Tbl"); 
dataGridView1.DataSource = ds.Tables["Tbl"];

Click Here
to read more.

Edited 2 Years Ago by cgeier

This article has been dead for over six months. Start a new discussion instead.