m3nhaq
m3nhaq

Reputation: 69

Object reference not set to an instance of an object. Please Help to solve error

I am new to C#.

Kindly tell me what`s wrong with this code. I am inserting data in data base using two input fields EndValueTextBox and StartValueTextBox .

I am receiving following error. "Object reference not set to an instance of an object"

private void buttonSave_Click(object sender, EventArgs e)
{
    connection = new System.Data.SqlClient.SqlConnection();
     da = new SqlDataAdapter();
    try
    {
        connection.ConnectionString = "Data Source=.\\SQLEXPRESS;AttachDbFilename='G:\\C#.Net\\Forms Practice\\WindowsFormsPractice1\\WindowsFormsPractice1\\WindowsFormsPractice1.mdf';Integrated Security=True;Connect Timeout=30;User Instance=True";
    }
    catch (System.Exception ex)
    {
        MessageBox.Show(ex.Message,"Connection String");
    }
    try
    {
        connection.Open();
        string sql = "insert into TBLWORKERS (first_name , last_name )" + " values('" + StartValueTextBox.Text + "', '" + EndValueTextBox.Text + ")";
        //SqlDataAdapter da = new SqlDataAdapter(query, connString);


        da.InsertCommand.CommandText = sql;

        da.InsertCommand.ExecuteNonQuery();

    }
    catch (System.Exception ex)
    {
        MessageBox.Show(ex.Message, "Connection open");
    } 
} 

Upvotes: 0

Views: 2475

Answers (5)

Tim
Tim

Reputation: 28530

Here's a minor rewrite of your code (not tested) that should take care of the SqlDataAdapter not having the connection object assigned and also demonstrates how to use parameterized queries to help defend against SQL Injection attacks:

private void buttonSave_Click(object sender, EventArgs e)
{

    try
    {
        // The using block will automatically dispose of your connection when
        // the block is exited and is considered standard practice.
        using (SqlConnection connection = new SqlConnection("Data Source=.\\SQLEXPRESS;AttachDbFilename='G:\\C#.Net\\Forms Practice\\WindowsFormsPractice1\\WindowsFormsPractice1\\WindowsFormsPractice1.mdf';Integrated Security=True;Connect Timeout=30;User Instance=True";))
        {

            SqlDataAdpter da = new SqlDataAdapter();

            connection.Open();

            // Assign the SqlConnection object to the SqlDataAdapter
            da.Connection = connection;

            // Parameterize the query as shown below
            string sql = "INSERT INTO TBLWORKERS(first_name, last_name) VALUES(@first_name, @last_name)";

            da.InsertCommand.CommandText = sql;

            // Add the values for the parameters
            da.InsertCommand.Parameters.Add("@first_name", SqlDbType.NVarChar, 25, StartValueTextBox.Text);
            da.InsertCommand.Parameters.Add("@last_name", SqlDbType.NVarChar, 25, EndValueTextBox.Text);

            // Execute the query - rows will have the number of rows
            // affected.  should be 1 in this case if succesful
            int rows = da.InsertCommand.ExecuteNonQuery();           
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message, "Connection open");
    }
}

Upvotes: 0

Damith
Damith

Reputation: 63095

string connetionString = "Data Source=.\\SQLEXPRESS;AttachDbFilename='G:\\C#.Net\\Forms Practice\\WindowsFormsPractice1\\WindowsFormsPractice1\\WindowsFormsPractice1.mdf';Integrated Security=True;Connect Timeout=30;User Instance=True";

SqlDataAdapter adapter = new SqlDataAdapter();

string sql =  "insert into TBLWORKERS (first_name , last_name )" + " values('" + StartValueTextBox.Text + "', '" + EndValueTextBox.Text + ")";

SqlConnection connection = new SqlConnection(connetionString);
try {
    connection.Open();
    adapter.InsertCommand = new SqlCommand(sql, connection);
    adapter.InsertCommand.ExecuteNonQuery();
} catch (Exception ex) {
    MessageBox.Show(ex.Message);
}

Upvotes: 0

Carmelo La Monica
Carmelo La Monica

Reputation: 765

At what point you are the exception? Probably those line

System.Data.SqlClient.SqlConnection connection = new System.Data.SqlClient.SqlConnection();
SqlDataAdapter da = new SqlDataAdapter();

Upvotes: 0

Fischermaen
Fischermaen

Reputation: 12468

This line da.InsertCommand.CommandText = sql; has to be in that way:

da.InsertCommand = new SqlCommand(sql); 

Upvotes: 1

SliverNinja - MSFT
SliverNinja - MSFT

Reputation: 31651

Your SqlDataAdapter is never assigned a connection to execute the query on. You need to associate the SqlConnection with the SqlDataAdapter during or after construction.

Upvotes: 2

Related Questions