I'm a beginner in programming and I'm trying to connect to a database. But when I click the "Search" button to browse the database and display 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 to C: \ database file). A database with the same name exists, or specified file can not be opened, or it is located on UNC share. ""
Below is my code for connecting and displaying 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();
}
}
}
}