从SQLite DB填充DataGridView(C#) [英] Fill DataGridView from SQLite DB (C#)
问题描述
我想从SQLite数据库填充一个datagridview。
我发现了很多方法。但是,我在我的dgv(项目,数量)中有预先存在的列。
目前,当我将数据库加载到dgv时,我得到插入到dgv中的数据列的列,而不是插入到正确列的实际数据。 p>
我的SQLite DB有一个包含三列的表(id PRIMARY KEY AUTO INCREMENT,item VARCHAR,quantity INTEGER)。
如何将DB加载到dgv的预先存在的列中?
填充dgv的当前代码:
private void button1_Click_1(object sender,EventArgs e)
{
SetConnection();
sqlconnection.Open();
sqlcmd = sqlconnection.CreateCommand();
string CommandText =SELECT * FROM table1;
sqlda = new SQLiteDataAdapter(CommandText,sqlconnection);
使用(dt = new DataTable())
{
sqlda.Fill(dt);
dataGridView1.DataSource = dt;
}
如果您不想打扰您可以使用SQLiteDataReader一行一行读取列并将其放在datagridview ..
private void button1_Click_1 sender,EventArgs e)
{
conn.Open();
SQLiteCommand comm = new SQLiteCommand(Select * From Patients,conn);
using(SQLiteDataReader read = comm.ExecuteReader())
{
while(read.Read())
{
dataGridView1.Rows.Add(new object [ ] {
read.GetValue(0),// U可以使用列索引
read.GetValue(read.GetOrdinal(PatientName)),//或者列名这样
read .getValue(read.GetOrdinal(PatientAge)),
read.GetValue(read.GetOrdinal(PhoneNumber))
});
}
}
}
I'm trying to fill a datagridview from an SQLite database.
I've found plenty of ways of doing this. However, I have pre-existing columns in my dgv (Item, Quantity).
Currently, when I load the DB to the dgv, I get columns of the DB inserted into the dgv instead of the actual data being inserted into the correct column.
My SQLite DB, has a table with three columns (id PRIMARY KEY AUTO INCREMENT, item VARCHAR, quantity INTEGER).
How do load the DB into the pre-existing columns of the dgv?
Current code for filling dgv:
private void button1_Click_1(object sender, EventArgs e)
{
SetConnection();
sqlconnection.Open();
sqlcmd = sqlconnection.CreateCommand();
string CommandText = "SELECT * FROM table1";
sqlda = new SQLiteDataAdapter(CommandText, sqlconnection);
using (dt = new DataTable())
{
sqlda.Fill(dt);
dataGridView1.DataSource = dt;
}
If you dont want to disturb the columns you can read the rows one by one using SQLiteDataReader and put it on to the datagridview..
private void button1_Click_1(object sender, EventArgs e)
{
conn.Open();
SQLiteCommand comm = new SQLiteCommand("Select * From Patients", conn);
using (SQLiteDataReader read = comm.ExecuteReader())
{
while (read.Read())
{
dataGridView1.Rows.Add(new object[] {
read.GetValue(0), // U can use column index
read.GetValue(read.GetOrdinal("PatientName")), // Or column name like this
read.GetValue(read.GetOrdinal("PatientAge")),
read.GetValue(read.GetOrdinal("PhoneNumber"))
});
}
}
}
这篇关于从SQLite DB填充DataGridView(C#)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!