Shubhankar Singh
Shubhankar Singh

Reputation: 3

SqlDataAdapter.Fill Invalid object name SQL

I am trying to load data from a sql database table into a datagridview.

I get the following:

An unhandled exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll Additional information: Invalid object name 'JournalItems'.

when calling this:

SqlDataAdapter.Fill(<dataset here>, <datatable name here>)

I know that JournalItems is a valid datatable in my database. I have also tried using "MyInitialCatalog.dbo.JournalItems" and "MyInitialCatalog.JournalItems" with no success.

Here is my code:

private void loadData_Click(object sender, EventArgs e)
    {
        string connectionString = "Data Source=myDataSource;Initial Catalog=MyInitialCatalog;Persist Security Info=True;User ID=myID;Password=myPassword";
        string sql = "SELECT * FROM JournalItems";
        SqlConnection connection = new SqlConnection(connectionString);
        connection.Open();
        sCommand = new SqlCommand(sql, connection);
        sAdapter = new SqlDataAdapter(sCommand);
        sBuilder = new SqlCommandBuilder(sAdapter);
        sDs = new DataSet();
        JournalItems = new DataTable();
        sAdapter.Fill(sDs, "JournalItems");
        sTable = sDs.Tables["JournalItems"];
        connection.Close();
        journalItemsDataGridView.DataSource = sDs.Tables["JournalItems"];
        journalItemsDataGridView.ReadOnly = true;
        saveData.Enabled = false;
        journalItemsDataGridView.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
    }

PS: here is the tutorial I am trying to follow: http://csharp.net-informations.com/datagridview/csharp-datagridview-database-operations.htm

Upvotes: 0

Views: 3250

Answers (2)

Caius Jard
Caius Jard

Reputation: 74585

PS here is the tutorial I am trying to follow: http://csharp.net-informations.com/datagridview/csharp-datagridview-database-operations.htm

Here is the tutorial set you should be following:

https://msdn.microsoft.com/en-us/library/fxsa23t6.aspx

Start with "Creating a simple data application"

Why do I advocate these over other ones you'll find on the web? Not an exhaustive list of reasons:

  • The creators of the programming language you're using, created them as a model of best practice for working with datasets
  • They suitably abstract(hide) much of the detail surrounding database interaction unless you need to get that low down and dirty
  • It will clean up your code no end
  • They're secure, fast and highly featured; you're automatically steered away from massive security no-no's like SQL injection
  • They're the step up from what you're doing now; you don't lay your windows forms out by hand writing statements for placing and setting the properties of every component: you use a visual designer that offers a rich and professional editing experience and generates quality code. This is no different

If you get on board with the way microsoft recommend you to do your data access, your code will look a bit more like this:

MyTypedDataSet ds = new MyTypedDataSet();
MyTypedTableAdapter ta = new MyTypedTableAdapter();
ta.Fill(ds, "my where clause parameter value");
myGridview.DataSource = ds.MyTypedTable;

Or, minimally:

myGridview.DataSource = new MyTypedTableAdapter().GetXXX();

No conenction strings, no button click handlers full of dodgy SQL; reusable, maintainable, easy to read code that doesn't take 100 lines to push the minutae of database connectivity around

Upvotes: 0

Zohar Peled
Zohar Peled

Reputation: 82474

Your Dataset have no table called "JournalItems".

Instead of

JournalItems = new DataTable();

Create the table inside the dataset:

sDs.Tables.Add("JournalItems");

Well, it turns out my initial answer was wrong. If the dataset does not have a table with the specified name, the dataAdapter should create it.

You need to make sure you are connected to the correct database and the correct schema. try adding the database name and schema name in the query itself:

SELECT * FROM DataBaseName.SchemaName.JournalItems

The rest of my original answer is still correct - only now that I've visited the link to the tutorial you are using, I need to add that you should avoid using class level variables to hold instances that implement the IDisposable interface - because then you can't use the using statement and you might end up not disposing instances you should dispose.

SqlConnection, SqlCommand, SqlDataAdapter and SqlCommandBuilder all implements the IDisposable interface, so you really should use them inside a using statement. btw, you don't need the SqlCommandBuilder for this code.
Your code should look more like this:

string connectionString = "Data Source=myDataSource;Initial Catalog=MyInitialCatalog;Persist Security Info=True;User ID=myID;Password=myPassword";
string sql = "SELECT * FROM JournalItems";
sDs = new DataSet();
sDs.Tables.Add("JournalItems");

using(var connection = new SqlConnection(connectionString))
{
    using(var sCommand = new SqlCommand(sql, connection))
    {
        using(var sAdapter = new SqlDataAdapter(sCommand))
        {
            sAdapter.Fill(sDs, "JournalItems");
        }
    }
}
journalItemsDataGridView.DataSource = sDs.Tables["JournalItems"];
journalItemsDataGridView.ReadOnly = true;
saveData.Enabled = false;
journalItemsDataGridView.SelectionMode = DataGridViewSelectionMode.FullRowSelect;

Upvotes: 1

Related Questions