0
I’m a beginner in programming and I’m trying to connect to a database. But by clicking the "Search" button to browse the database and exbir values on my screen, the following error is generated through a messagebox that I put in Catch:
""An Attempt to attach an auto-named database for file C: (path database file). A database with the same name exists, or specified file cannot be opened, or it is Located on UNC share.""
Below is my code to connect and display values:
namespace trenodb
{
public partial class Form1 : Form
{
static string strDb = "Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=\"C:\\Users\aRtHuRz\\Documents\\Visual Studio 2015\\Projects\\trenodb\\trenodb\\dbTrenodb.mdf\";Integrated Security=True;Connect Timeout=30";
public Form1()
{
InitializeComponent();
}
private void btnPesquisar_Click(object sender, EventArgs e)
{
string pesquisar = "SELECT * FROM Table WHERE [Id] = " + txtID;
SqlConnection conexao = new SqlConnection(strDb);
SqlCommand cmd = new SqlCommand(pesquisar, conexao);
SqlDataReader DR;
try
{
conexao.Open();
DR = cmd.ExecuteReader();
if (DR.Read())
{
txtID.Text = DR.GetValue(0).ToString();
txtNome.Text = DR.GetValue(1).ToString();
txtFone.Text = DR.GetValue(2).ToString();
txtEndereço.Text = DR.GetValue(3).ToString();
DR.Close();
} cmd.Dispose();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conexao.Close();
}
}
}
}
you have tried to configure your connection string differently, by the project properties ?
– Diego Farias
No, how could I do that ? .
– tutiBits
You right-click on your project -> properties -> On the screen that opens, look for the Settings tab, then you create a name, choose the Connection String type, then click the Value column, it will give you the option to create the connection to your database. As soon as you finish, the connection string will appear to you in that same column. You have the option to copy and put in place of the string you are currently using or use this string through the project properties.
– Diego Farias