我目前正在使用 Windows 窗体和 SQLite 创建一个小型应用程序。在阅读了一些教程后,我实现了这种数据检索方法:
public DataTable GetDataTable(ref SQLiteDataAdapter adapter, string sql)
        {
            DataTable dt = new DataTable();
            // Connect to database.
            using (SQLiteConnection connection = new SQLiteConnection(connectionString))
            // Create database adapter using specified query
            using (adapter = new SQLiteDataAdapter(sql, connection))
            // Create command builder to generate SQL update, insert and delete commands
            using (SQLiteCommandBuilder command = new SQLiteCommandBuilder(adapter))
            {
                // Populate datatable to return, using the database adapter                
                adapter.Fill(dt);
            }
            return dt;
        }
(以及另一个不以 SQLiteDataAdapter 作为参数的 GetDataTable)
我有三个类,我们称它们为 UI、Link 和 Database。UI 除了显示数据并在用户交互时引发事件之外什么都不做。Link 创建 Database 和 SQLiteDataAdapter,通过上述方法检索数据表,并将其绑定到 UI 上的数据网格视图。用户不能通过数据网格视图改变表格,但应该通过一些文本框来改变。(这是否会使表格绑定到 dgv 过时?)
使用适配器将用户输入从文本框获取到数据库的最佳方式是什么?或者我应该使用 DataReader 和一些 Insert 方法而不是适配器?
众所周知,UI 通过 Get 方法公开其控件。有更好的解决方案吗?
private void Initialize()
{
    // Subscribe to userInterface events
    userInterface.DataGridViewSelectionChanged += new EventHandler(userInterface_DataGridViewSelectionChanged);
    userInterface.NewClicked += new EventHandler(userInterface_NewClicked);
    userInterface.SaveClicked += new EventHandler(userInterface_SaveClicked);
    // Get dataGridView from userInterface and bind to database
    bindingSource = new BindingSource();
    bindingSource.DataSource = database.GetDataTable(ref adapter, "SELECT * FROM SomeTable");
    userInterface.GetDataGridView().DataSource = bindingSource;
}  
void userInterface_DataGridViewSelectionChanged(object sender, EventArgs e)
{
    if (userInterface.GetDataGridView().SelectedRows.Count != 0)
    {
        DataGridViewRow row = userInterface.GetDataGridView().SelectedRows[0];
        userInterface.GetIDTextBox().Text = row.Cells["PrimaryKey].Value.ToString();
        userInterface.GetOtherIDTextBox().Text = row.Cells["ForeignKey"].Value.ToString();
        DataTable dt = database.GetDataTable("SELECT * from SomeTable WHERE ForeignKey=" + row.Cells["ForeignKey"].Value);
        userInterface.GetLastNameTextBox().Text = dt.Rows[0]["LastName"].ToString();
        userInterface.GetFirstNameTextBox().Text = dt.Rows[0]["FirstName"].ToString();
        userInterface.GetCompanyTextBox().Text = dt.Rows[0]["Company"].ToString();
    }            
}
void userInterface_NewClicked(object sender, EventArgs e)
{
    // Get all text boxes and clear them
    // Let the UI take care of this by itself?                     
}
void userInterface_SaveClicked(object sender, EventArgs e)
{
        // Get text/data from all text boxes and insert (or update if editing table) into database
        // adapter.Update(...)?
}
干杯!