C#:将DataGridView绑定到应用程序目录中的数据库文件 [英] C#: Bind DataGridView to a database file in the application directory

查看:111
本文介绍了C#:将DataGridView绑定到应用程序目录中的数据库文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前在 c:\temp中有一个绑定到sqlite数据库的DataGridView。我使用VS2008 GUI绑定它。我希望它绑定到运行应用程序的任何目录中的数据库。我可以看到该路径已被硬编码为 c:\temp\myapp.db,但是如果我在生成的代码中对其进行更改,那么在重新编译时会被覆盖吗?

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?

如何设置它,以便DataGridView连接到应用程序所在目录中的sqlite db文件?

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

我是Winforms编程的新手,所以逐步了解它的细节将非常有用。

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

UPDATE

我想我知道如何获得化身证书(见下文);问题是当VS生成数据库访问代码时让DataGridView使用它。

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);

也许无法做到吗?
也许我需要写一个我打算做的DAL-如果有的话,现在只是想要一种快速解决方案。

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.

推荐答案

使用预期的文件名组合应用程序的启动路径:

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

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

这将包括可执行文件的运行路径。
然后可以将此文件名变量用作SQLiteConnection对象上的Database属性:

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;

更新:要通过代码绑定网格,请参见此MSDN文章。它适用于MSSQL,但SQLite从Data命名空间类继承到对象是可互换的。

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.

这篇关于C#:将DataGridView绑定到应用程序目录中的数据库文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆