简体   繁体   中英

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");
    } 
} 

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.

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

da.InsertCommand = new SqlCommand(sql); 
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);
}

At what point you are the exception? Probably those line

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

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");
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM