Arindam Das
Arindam Das

Reputation: 699

How to connect to .sdf file in Winform application using C#?

I am trying to connect a .sdf file with my winform. here's what i am trying to do :

SqlConnection con = new SqlConnection();
        con.ConnectionString=@"Data Source=D:\TestWinform\MyDB.sdf;Persist Security Info=True";
        SqlCommand cmd = new SqlCommand();
        cmd.CommandType = CommandType.Text;
        cmd.CommandText = "insert into User(Name) values('" + txt.Text + "')";
        cmd.Connection = con;


        con.Open();   // giving exception in this line
        cmd.ExecuteNonQuery();
        con.Close();

but i am facing a problem, on con.Open() its giving this exception

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: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified) 

what should i do, i guess that it couldn't find the file but the .sdf file is there on that location So pls help me on this

Upvotes: 2

Views: 21372

Answers (1)

Toan Vo
Toan Vo

Reputation: 1298

Your connection object is wrong. You are using Sql compact so you have to use SqlCeConnection. The SqlConnection used to connect to SQL Server.

Follow the link to sort your problem.

Here is sample.

Upvotes: 7

Related Questions