问题
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