我试图在 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;
}
}
另外,这是程序运行的屏幕截图,可能有助于更好地解释我遇到的问题:https://i.stack.imgur.com/kOUhb.jpg https://i.stack.imgur.com/kOUhb.jpg
我知道表中有数据,但我只是不知道为什么在执行 btnSelect_tbl_Click 方法时它没有出现在数据网格中。
任何帮助,将不胜感激。
Thanks!
根据教程如何:将数据绑定到 Windows 窗体 DataGridView 控件 https://learn.microsoft.com/en-us/dotnet/framework/winforms/controls/how-to-bind-data-to-the-windows-forms-datagridview-control,你缺少一个绑定源 https://learn.microsoft.com/en-us/dotnet/api/system.windows.forms.bindingsource?view=netframework-4.7将数据从数据源绑定到表到 DataGrid 的组件。
初始化BindingSource
在班级中名列前茅,如下所示:
private BindingSource bindingSource1 = new BindingSource();
然后在按钮单击方法顶部附近的 sql 之前添加以下行:
qbcMemDataView.DataSource = bindingSource1;
最后更改最后一行代码
qbcMemDataView.DataSource = dataTbl;
to
bindingSource1.DataSource = dataTbl;
尝试一下,看看它是否适合你。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)