简体   繁体   中英

How to connect to SQL Server CE using ADO.NET

I have a EntityModel created from ADO.NET that connects to my database. I want to fill a DataGridview . For that I'm following this code:

using System.Data;
using System.Data.SqlServerCe;
using System.Windows.Forms;

namespace WindowsFormsApplication5
{
public partial class Form1 : Form
{
public Form1()
{
    InitializeComponent();
    FillData();
}

void FillData()
{
    // 1
    // Open connection
    using (SqlCeConnection c = new SqlCeConnection(
    Properties.Settings.Default.DataConnectionString))
    {
    c.Open();
    // 2
    // Create new DataAdapter
    using (SqlCeDataAdapter a = new SqlCeDataAdapter(
        "SELECT * FROM Animals", c))
    {
        // 3
        // Use DataAdapter to fill DataTable
        DataTable t = new DataTable();
        a.Fill(t);
        // 4
        // Render data onto the screen
        dataGridView1.DataSource = t;
    }
    }
}
}

This code comes from a Web Page, so I'm trying to adapt it to my ADO.NET model. So, as I'm not sure where the Properties.Settings.Default.DataConnectionString comes from, I thought it was the connection string used to connect to my database, so, following my Entity Model , I wrote this to get the connection string:

SqlCeConnection c = new SqlCeConnection(db.Connection.ConnectionString);

Where db is my Entity Model created like this:

private dbEntities db = new dbEntities();

But this db.Connection.ConnectionString returns this: "name= dbEntities" , so I changed it to db.Connection.DataSource , that returns this string:

"C:\\\\Users\\\\user\\\\Documents\\\\Visual Studio 2010\\\\Projects\\\\ProjectName\\\\MySQLProject\\\\bin\\\\Debug\\\\db.sdf" string

But it says that the string format is not adjusted (obviously...). I'm using SQL Server, but I'm not sure how to get that connection :(

The Properties.Settings.Default.DataConnectionString says this:

        Properties.Settings.Default.dbConnectionString  'System.Windows.Forms.PropertyStore' 

does not contain a definition for 'Settings' and no extension method 'Settings' accepting a first argument of type 'System.Windows.Forms.PropertyStore' could be found (are you missing a using directive or an assembly reference?)

The message does not mean the connection string is in wrong format! Is says that there are no settings in your project.

Are you sure that you created a respective setting? To edit them, double click the "Properties" entry in your project, then switch to the "Settings" tab. If there's no entry dbConnectionString , create one.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM