Arjento Deathbroker
Arjento Deathbroker

Reputation: 9

Insert into SQL DB doesn't work

 SqlCommand cmd = new SqlCommand();
        SqlConnection con = new SqlConnection();
        string checkRadioButton()
        {
            string rbdText;
            if(RadioButton1.Checked)
            {
                rbdText = RadioButton1.Text;
            }
            else
            {
                rbdText = RadioButton2.Text;
            }
            return rbdText;
        }



        protected void Button1_Click(object sender, EventArgs e)
        {
            SqlCommand cmd = new SqlCommand(" insert into Registration values(@Name, @Gender, @MobileNumber, @EmailID, @UserID, @Password, @Address, @Country)", con);
            cmd.Parameters.AddWithValue("@Name", TextBox1.Text);
            cmd.Parameters.AddWithValue("@Gender", checkRadioButton());
            cmd.Parameters.AddWithValue("@MobileNumber", TextBox2.Text);
            cmd.Parameters.AddWithValue("@EmailID", TextBox3.Text);
            cmd.Parameters.AddWithValue("@UserID", TextBox5.Text);
            cmd.Parameters.AddWithValue("@Password", TextBox6.Text);
            cmd.Parameters.AddWithValue("@Address", TextBox8.Text);
            cmd.Parameters.AddWithValue("@Country", DropDownList1.SelectedItem.Value);
            cmd.ExecuteNonQuery();
            con.Close();
            Response.Redirect("Homepage2.aspx");

        }

This is my aspx.cs file for registration page. There is no compilation error, but after the Button1_Click event executed, the registration data is not saved into the database.

Upvotes: 0

Views: 78

Answers (2)

Lews Therin
Lews Therin

Reputation: 3777

As others have mentioned, the answer to your question is that you are missing a connection string as a parameter for the instantiation of your SqlConnection object:

SqlConnection con = new SqlConnection("connection string goes here");

However, there are a few other things I would like to recommend you change in your code.

Properly releasing of unmanaged resources

Any class that implements the IDisposable interface needs to be disposed of properly. What that means is calling the Dispose() method, or wrapping the instantiation of the object in a using block (I would highly recommend this route if possible as it is much simpler).

So, for example, SqlConnection implements IDisposable, so I would change this:

SqlConnection con = new SqlConnection(); 

to this:

using (SqlConnection con = new SqlConnection())
{
    // ...
}

You would need to make these changes for SqlCommand as well.

Use of try...catch blocks for code that could throw exceptions

Any code that could throw an exception should be wrapped in a try...catch block. What this does is prevent your application from crashing when an exception is thrown. Exceptions can be thrown in places you would not expect that have nothing to do with your code.

Take SqlConnection for example. If your network connection suddenly stops working and your code calls SqlConnection.Open(), an exception would be thrown and your application would crash. Wrapping this line in a try...catch block would prevent the app from crashing and allow you to handle the exception "gracefully" (by logging the error and continuing running the application if possible).

using (var connection = new SqlConnection("Server=SQLServerName;Integrated Security=True;"))
{
    try
    {
        connection.Open()
    }
    catch (Exception ex)
    {
        // Do something with the exception
    }
}

Moving hardcoded SQL statements to Stored Procedures/Functions

If you put your SQL statements directly in your source code (commonly called "hardcoding"), you then have to re-compile and re-deploy your entire application if that SQL statement has to change in the future.

Instead, you can extract SQL statements into Stored Procedures or Functions and call those from your code. That way, when the SQL statement needs to change, you don't need to re-compile and re-deploy your application; simply update the stored procedure/function.

There are a few more parts of your code that could be refactored to be simpler, but this post is already far larger than I initially intended, so I will stop here.

Upvotes: 0

Alex M
Alex M

Reputation: 2548

You would need to add a connection string into the SQLConnection constructor. The connection string itself is usual to keep in the web.config. So the code could be similar to:

var connectionString = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString;
using (SqlConnection connection = new SqlConnection(connectionString))
{
    connection.Open();
    // Do your insert here;
}

Upvotes: 1

Related Questions