Partha
Partha

Reputation: 21

Getting error SqlException was unhandled by user code

I'm creating a Registration form for new user sign up. Im getting the following error. I searched for solution on google, but none of them helped me.

Error : A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server).

Could you please help me out with this?

Code :

public partial class Registration : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        SqlConnection con = new SqlConnection(@"Data Source=.\;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True;");
        con.Open();
        SqlCommand cmd = new SqlCommand("Select * from regform where username='" + TextBox1.Text + "'", con);
        SqlDataReader dr = cmd.ExecuteReader();

        if (dr.Read())
        {
            Label1.Text = "User Name is Already Exist";
        }
        else
        {
            Label1.Text = "UserName is Available";
        }
        con.Close();
    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        SqlConnection con = new SqlConnection(@"Data Source=.\;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True;");
        con.Open();
        String str = "Insert into regform values ( '" + TextBox1.Text + "','" + TextBox2.Text + "','" + TextBox4.Text + "','" + TextBox5.Text + "')";
        SqlCommand cmd = new SqlCommand(str, con);
        cmd.ExecuteNonQuery();

        Session["name"] = TextBox1.Text;
        Response.Redirect("Default.aspx");
        con.Close();
    }
}

Upvotes: 2

Views: 17305

Answers (3)

marc_s
marc_s

Reputation: 754278

Your connection string seems off

Data Source=.\;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True;

Using the AttachDbFilename=... element indicates you're using SQL Server Express, but the Express default installation would be using the SQLEXPRESS instance name - so your connection string should be

Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True;

Have you tried with this connection string? Any luck?

If that doesn't work - can you make sure what edition of SQL Server you have installed? Connecting to it in Management Studio - what do you use as server name?? And if you're connected - what does SELECT @@Version return?

Upvotes: 1

Olivier Jacot-Descombes
Olivier Jacot-Descombes

Reputation: 112279

The exception suggests that your connection string is wrong.

Isn't Initial Catalog=InstanceDB missing from your connection string? Where InstanceDB is the name of your database.


Use command parameters! If you don't, you will face several issues:

  • You will be threatened by SQL injection attacks!
  • You will have to deal with the special handling of null entries.
  • You will have to escape quotes in strings.
  • You will have to use the right formatting for date values.
  • Lengthy string concatenations look ugly.
SqlCommand cmd = new SqlCommand(
    "SELECT * FROM regform WHERE username = @usr", con);
cmd.AddWithValue("@usr", TextBox1.Text);

Do the same for the insert statement.

Upvotes: 0

MethodMan
MethodMan

Reputation: 18843

utilize this example taken from Retrieving Data Using a DataReader you will see quickly where you are making the slight code mistake

static void HasRows(SqlConnection connection)
{
    using (connection)
    {
        SqlCommand command = new SqlCommand(
          "SELECT CategoryID, CategoryName FROM Categories;",
          connection);
        connection.Open();

        SqlDataReader reader = command.ExecuteReader();

        if (reader.HasRows)
        {
            while (reader.Read())
            {
                Console.WriteLine("{0}\t{1}", reader.GetInt32(0),
                    reader.GetString(1));
            }
        }
        else
        {
            Console.WriteLine("No rows found.");
        }
        reader.Close();
    }
}

change your code here

SqlCommand cmd = new SqlCommand("Select * from regform where username='" + TextBox1.Text + "'", con); 

Either create a Property or even better a Stored Procedure

Upvotes: 0

Related Questions