Click here to Skip to main content
15,074,394 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I have a C# windows application with a local db (SQL server express). I added the SQL server express to the application directory, every thing is working fine, i can save to the database, but i found out that there is a copy of the database in the BIN folder, and that is where my saved records are. I am trying to bind a dataGridView to view saved records, the code runs without error, but the grid is not loaded with data as the dataSet table is null.

What I have tried:

private void BindDataGridView()
{
    try
    {
        var select = "SELECT DISTINCT [Country],[State],[City] FROM dbo.StaffRecord ORDER BY [Country] ASC,[State] DESC";
        var c = new SqlConnection(connstring);
        var dataAdapter = new SqlDataAdapter(select, c);

        var ds = new DataSet();
        dataAdapter.Fill(ds);
        dataGridView1.ReadOnly = true;
        dataGridView1.DataSource = ds.Tables[0];

    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
}


My Connection string:

<add name="connection" connectionString = "Data Source=(localdb)\MSSQLLocalDB; Initial catalog=StaffRecord; Integrated Security=true;AttachDBFilename=|DataDirectory|\Database1.mdf;" providerName="System.Data.SqlClient" />


Please i wont to be able to bind the DataGridView to the version of the local DB in the BIN folder since the Records are saved there. Thanks
Posted
Updated 25-Nov-19 22:31pm
v3

1 solution

Quote:
To connect to a specific database by using the file name, connect using a connection string similar to Server=(LocalDB)\MSSQLLocalDB; Integrated Security=true ;AttachDbFileName=D:\Data\MyDB1.mdf.

SQL Server Express LocalDB - SQL Server | Microsoft Docs[^]

But be warned about AttachDBFileName:
Quote:
This feature will be removed in a future version of Microsoft SQL Server. Avoid using this feature in new development work, and plan to modify applications that currently use this feature.

More information here: Bad habits: Using AttachDBFileName[^]


If you don't want all these headaches caused by SQL Server, and your needs are simple, try LiteDB, see: best-databases-for-a-small-net-application~litedb[^]
   
v3
Comments
Uwakpeter 26-Nov-19 4:25am
   
Thanks RickZeeland. There is requirement to use SQL Server Database. And i have updated my code with the connection string i am using.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900