0

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");
    } 
} 
4
  • A warning about the way you create your SQL. You're having the security risk of Sql Injection. This means that if someone will enter some sql in one of those texboxes instead of a normal start/end value that sql will be executed against the database (for example a 'drop table' command!) Commented Oct 27, 2011 at 5:56
  • @Wouter: The OP doesn't understand what you mean. How about providing a link to a SQL injection article that describes how to parameterize? Commented Oct 27, 2011 at 5:58
  • 2
    @RobertHarvey you're right :) This link: csharp-station.com/Tutorials/AdoDotNet/Lesson06.aspx has a nice introduction about how to construct a sql query Commented Oct 27, 2011 at 6:01
  • 1
    A single try/catch statement will also be sufficient - you don't need multiple. Commented Oct 27, 2011 at 6:02

5 Answers 5

2

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.

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

1 Comment

If the OP is truly new to C#, this is Greek to him. How about a code sample?
1

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

da.InsertCommand = new SqlCommand(sql); 

1 Comment

You can do it the OP's way too, using a string.
0

At what point you are the exception? Probably those line

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

1 Comment

neither of these lines could be the exception - they are simple ctors.
0
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);
}

Comments

0

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

Comments

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.