【问题标题】:SQLite Data Adapter not displaying dataSQLite 数据适配器不显示数据
【发布时间】:2018-01-12 23:38:53
【问题描述】:

我正在尝试在我的 Windows 窗体应用程序中填充数据网格视图,但是当我执行选择查询时,数据库没有返回任何内容。我在这个网站上查看了关于这个主题的其他问题,但找不到任何可以解决我的问题的东西。

数据视图表的名称是 qbcMemDataView,数据源是一个名为 sqlite_dbDataSet1 的 sqlite 数据集

这是我的代码:

public Form1()
{
    InitializeComponent();

    dbConnection = new SQLiteConnection("Data Source=sqlite_db.sqlite;Version=3");

    dbConnection.Open();

    string[] restrictions = new string[4];

    restrictions[2] = "test_table_mom";

    using (DataTable dTbl = dbConnection.GetSchema("Tables", restrictions))
    {
        for (int i = 0; i < dTbl.Rows.Count; i++)
        {
            tblChooser.Items.Add(dTbl.Rows[i].ItemArray[dTbl.Columns.IndexOf("TABLE_NAME")].ToString());
        }

        if (tblChooser.Items.Count > 0)
        {
            tblChooser.SelectedIndex = 0;
        }
    }  
}

private void btnSelect_tbl_Click(object sender, EventArgs e)
{

    string sql = "SELECT id, name FROM test_table_mom";

    using (SQLiteDataAdapter dbAdapter = new SQLiteDataAdapter(sql, dbConnection))
    {
        DataTable dataTbl = new DataTable();

        dbAdapter.Fill(dataTbl);

        qbcMemDataView.DataSource = dataTbl;
    }
}

另外,这是运行程序的屏幕截图,可能有助于更好地解释我遇到的问题:http://imgur.com/j9ffeVi

我知道表格里面有数据,只是不知道为什么在执行btnSelect_tbl_Click方法时它没有出现在数据网格中。

任何帮助将不胜感激。

谢谢!

【问题讨论】:

    标签: c# sqlite


    【解决方案1】:

    根据教程 How to: Bind Data to the Windows Forms DataGridView Control,您缺少一个 BindingSource 组件,该组件将数据从数据源绑定到您的表到 DataGrid。

    像这样初始化类顶部的BindingSource

    private BindingSource bindingSource1 = new BindingSource();
    

    然后在你的按钮点击方法顶部附近的sql前添加一行:

    qbcMemDataView.DataSource = bindingSource1;
    

    最后修改最后一行代码

    qbcMemDataView.DataSource = dataTbl;
    

    bindingSource1.DataSource = dataTbl;
    

    试试看它是否适合你。

    【讨论】:

      【解决方案2】:

      注意:我不确定这是否适用于 c#,但也许它是通用修复。

      Android 内置适配器等使用 _id 作为 id 字段的名称。另一个问题是 _id 和 id,它在 android 中没有很好的记录。

      About "_id" field in Android SQLite

      您可以在选择中使用这种重命名技术,但它会变得混乱,您可能无法捕捉到所有出现的情况。

      string sql = "SELECT id _id, name FROM test_table_mom";
      

      我的意见:回去把你的 db id 重构为 _id。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-05-29
        • 2021-12-07
        • 1970-01-01
        • 1970-01-01
        • 2021-09-13
        • 1970-01-01
        • 2014-04-14
        • 2016-05-18
        相关资源
        最近更新 更多