0

I'm trying to use a SELECT query with SqlDataAdapter to fill a dataset, the problem is occurring in this parameters.add line. The SqlConnection is OK.

Dim dt As New DataSet()

Using adapter As New SqlDataAdapter("SELECT * from TAB_Movimentos WHERE Banco = @Banco", New SqlConnection(MontaStringConexaoSQLServer()))
    adapter.UpdateCommand.Parameters.Add("@Banco", SqlDbType.Int)
    adapter.Fill(dt)
End Using

Returning:

Referência de objeto não definida para uma instância de um objeto." (BR)

Object reference not set to an instance of an object." (EN)

1 Answer 1

1

Indeed; you've set a SELECT query but that doesn't mean that the DataAdapter's UpdateCommand is set to anything

        Dim dt As New DataTable()
        Using adapter As New SqlDataAdapter("SELECT * from TAB_Movimentos WHERE Banco = @Banco", New SqlConnection(MontaStringConexaoSQLServer()))
            adapter.SelectCommand.Parameters.Add("@Banco", SqlDbType.Int).Value = 1234
            adapter.Fill(dt)
        End Using

You don't need to use a DataSet (a collection of datatables) - a DataAdapter knows how to fill a DataTable. Using a dataset for this is like using an array of strings when all you really want is a single string

You also forgot to give the parameter a value. I gave it 1234

Sign up to request clarification or add additional context in comments.

3 Comments

Nice! It worked... One more question, I got confuse about DataSet, I understood your explain but I tried to googled it without success...
You can think of a DataTable as a thing which has zero or more rows. You could also think of a DataSet as a thing that has zero or more DataTables. A DataAdapter can "fill" and empty DataTable, but it can also fill an empty DataSet (in which case you get a DataSet with a single DataTable containing your rows). If you just have a single table, fill a DataTable.
A DataSet is like an array of DataTables and is the conceptual equivalent of an entire database. A DataTable is like an array of DataRows and is the equivalent of a single DB table. If you want a DataTable, use a DataTable, not a DataSet. After all, if you want a single string you write Dim s as String = "Hello World", you don't write Dim s(100) as New String s(0) = "Hello World". No-one make an array of 100 strings if all they want is a string. You'll nearly never need to use a DataSet if you only user use a DataAdapter, so if nothing else, just remember "DataTable, not DataSet"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.