panda007
panda007

Reputation: 17

An unhandled exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll

I am making simple application. It has only one button "Add" to add new data in database. First it didn't insert data, i checked it when i press right button on table and then select "Show Table Data" it showed nothing. And when i stated program again, datagridview also was empty. After that i changed my database option "Copy to Output" in Solution Explorer to "Do not Copy" it appears that error. When I press that button, it occurs with that exception

An unhandled exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll

Additional information: An attempt to attach an auto-named database for file c:\users\sanan\documents\visual studio 2013\Projects\Test\Test\bin\Debug\Base.mdf failed. A database with the same name exists, or specified file cannot be opened, or it is located on UNC share.

Also I have database called "Base.mdf" with table "Stu" in project folder (not in debug)

This is code to add

    private void Form1_Load(object sender, EventArgs e)
    {
        //this.stuTableAdapter.Fill(this.baseDataSet.Stu);
    }

    private void button1_Click(object sender, EventArgs e)
    {

        SqlConnection connection = new SqlConnection
            (@"Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\Base.mdf;Integrated Security=True;");
        connection.Open();
        SqlCommand command = new SqlCommand("insert into Stu values(@id,@Name,@SurName)",connection);
        command.Parameters.AddWithValue("@id", int.Parse(textBox1.Text));
        command.Parameters.AddWithValue("@Name", textBox2.Text);
        command.Parameters.AddWithValue("@SurName", textBox3.Text);

        command.ExecuteNonQuery();

        this.stuTableAdapter.Fill(this.baseDataSet.Stu);
    }
}

}

Upvotes: 0

Views: 1548

Answers (1)

Andi
Andi

Reputation: 57

though I do not know the final (working) solution to this problem, the cause most likely has to do with your database.mdf residing in your project directory. The settings of the .mdf and .ldf in the properties window might show always copy if newer.
The Database or Server Explorer looks in your project directory and changes are done in the subfolder /bin/debug. Somehow VS gets confused. Have a look here:

Why saving changes to a database fails

Regards Andi

Upvotes: 0

Related Questions