0

i am using VS.NET 2008 with MS SQL server 2005 to develop a window form application but everytime i got new error in connection or after conected,

in my current code the connection opened but doesnt work after that in transaction of queries. maybe i have problem while making new DB or new datasource also m not that satisfy how to get Connecting String

this is my code....

/////////
private void button1_Click(object sender, EventArgs e)
    {
        try
        {
            //setData();
            string ConnectingString = @"Data Source=SERVER1\SQLEXPRESS;Initial Catalog=Alkawthar;Integrated Security=True;Pooling=False";
            qry = "SELECT * FROM Table1";
            //reader = db.select_data(qry);
            ds1 = new DataSet();
            conn = new SqlConnection(ConnectingString);

            conn.Open(); 
            MessageBox.Show("connection opened");
            da.Fill(ds1,"Workers");
            NavigateRecords();
            MaxRows = ds1.Tables["Workers"].Rows.Count;
            string sql = "SELECT * From tblWorkers";
            da = new System.Data.SqlClient.SqlDataAdapter(sql, conn);
            conn.Close();
            MessageBox.Show("connection closed");
            conn.Dispose();
        }
        catch (Exception ex)
        {
            MessageBox.Show("exception");
            MessageBox.Show(ex.Message);
        }
    }
/////////////////

Fill throws an exception also when i use reader it return null although there is data in DB thanks

3
  • 3
    What is the exception you are getting? Commented Nov 8, 2010 at 12:43
  • 1
    You don't need both conn.Close() and conn.Dispose() (Dispose calls Close). You should use the using (conn = new Connection()) { ... } pattern instead of explicitly calling Dispose. Commented Nov 8, 2010 at 12:45
  • @Albin: messagebox i put it on purpose to find xactly from where is the xception, thanx i need solution not advices Commented Nov 9, 2010 at 6:24

3 Answers 3

2

The most obvious problem here is that you access the SqlDataAdapter before initializing it. That will cause a null reference exception. Try to move the line da = new SqlDataAdapter(...) to the line before you do the da.Fill(...).

Edit:

No, wait! I see that you do two queries and two fills in there. You need to initialize the SqlDataAdapter before doing the first fill. Then you should get rid of the null reference exception.

Edit again:

Also, as commented, you don't need call both the SqlConnection.Close and SqlConnection.Dispose methods. As long as you use the SqlDataAdapter you don't even need to do the SqlConnection.Open on the connection, for the Fill method will do all that for you. As long as the connection starts out being closed, the Fill method will close it again for you when it is done.

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

6 Comments

@Turrau: Haha... +1'ed you too :-)
after editing now the exception is :: invalid object name'tblWorkers' which name of the table in my data base
@salman: Yep. That is the one you will get if your variable isn't initialized. You use the da object before setting it to anything.
@salman: The invalid object name message means that you are trying to access an object that either doesn't exist or that your user cannot access. Try to run the same query in the query browser or sql management tool and see if it runs there. Also make sure that the user you logs on as actually can access the table. Finally, you may want to try to prefix the table name with dbo. or whatever namespace you have defined the table in.
is it possible that my DB didnt add properly?
|
1

A few points of advice;

  1. Like Turrau and Rune say, your stuff is in the wrong order. Open connection, Execute SQL - Get raw data, close connection. Then do your counting, etc.
  2. Don't put message box or logging calls anywhere in between the connection opening and closing. This has burned me before, where the those calls can affect the SQL call because they fudge the exception details and make it difficult to trace. This is also applicable when using a SQL data reader.
  3. Put the SQL stuff in a using block.

Try this...

    string _connStr = @"Data Source=SERVER1\SQLEXPRESS;Initial Catalog=Alkawthar;Integrated Security=True;Pooling=False";
    string _query = "SELECT * FROM Workers";
    DataSet _ds = new DataSet();

    try
    {

        using (SqlConnection _conn = new SqlConnection(_connStr))
        {
            SqlDataAdapter _da = new SqlDataAdapter(_query, _conn);
            _conn.Open();
            _da.Fill(_ds);
        }

        // insert null dataset or invalid return logic (too many tables, too few columns/rows, etc here.


        if (_ds.Tables.Count == 1)
        { //There is a table, assign the name to it.
            _ds.Tables[0].TableName = "tblWorkers";
        }

        //Then work with your tblWorkers

    }
    catch (Exception ex)
    {
        Console.Write("An error occurred: {0}", ex.Message);
    }

Comments

1

Seems to me, that you use your DataAdapter before initialization. Do you get a NullReferenceException?

da.Fill(ds1,"Workers"); 
// ...
da = new System.Data.SqlClient.SqlDataAdapter(sql, conn); 

2 Comments

object refrence is not set to an instance of the object
Yes, this is an NullReferenceException. Have a look at Rune's answer, it should help you.

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.