C#: Bind DataGridView to a database file in the application directory

前提是你 提交于 2019-12-25 06:23:15

问题


I currently have a DataGridView bound to an sqlite database in "c:\temp". I bind it using the VS2008 GUI. I would like it to bind to a database in whatever directory the application is run from. I can see where the path has been hardcoded to "c:\temp\myapp.db", but if I change it in the generated code it will get overwritten when I recompile I think?

How do I set it up so that the DataGridView connects to an sqlite db file in whatever directory the application is in?

I'm very new to Winforms programming so step by step detail would be greatly appreciated.

UPDATE

I think I know how to get the cwd (see below); the problem is getting the DataGridView to use it when the db access code is generated by VS.

string cwd =    System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location);

Perhaps it can't be done? Perhaps I need to write a DAL, which I was planning to do - just wanted a quick solution for now if there is one.


回答1:


Combine the application's startup path with the expected filename:

string filename = System.IO.Path.Combine(Application.StartupPath, "datafile.db");

This will include the path to the executable wherever it is run. You can then use this filename variable as the Database property on the SQLiteConnection object:

        System.Data.SQLite.SQLiteConnection conn = new System.Data.SQLite.SQLiteConnection();
        // ... your connection setup code here
        conn.Database = filename;

Update: To bind the grid via code see this MSDN article. It applies to MSSQL but SQLite inherits from the Data namespace classes to the objects are interchangeable.



来源:https://stackoverflow.com/questions/5483320/c-bind-datagridview-to-a-database-file-in-the-application-directory

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!