[英]Fill DataGridView from SQLite DB (C#)
I'm trying to fill a datagridview from an SQLite database. 我正在尝试从SQLite数据库填充datagridview。
I've found plenty of ways of doing this. 我发现了很多这样做的方法。 However, I have pre-existing columns in my dgv (Item, Quantity). 但是,我的dgv中有预先存在的列(项目,数量)。
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. 目前,当我将DB加载到dgv时,我将DB的列插入到dgv中,而不是将实际数据插入到正确的列中。
My SQLite DB, has a table with three columns (id PRIMARY KEY AUTO INCREMENT, item VARCHAR, quantity INTEGER). 我的SQLite DB有一个包含三列的表(id PRIMARY KEY AUTO INCREMENT,item VARCHAR,quantity INTEGER)。
How do load the DB into the pre-existing columns of the dgv? 如何将数据库加载到dgv的预先存在的列中?
Current code for filling 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);
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 into the datagridview.. 如果您不想打扰列,可以使用SQLiteDataReader逐行读取行并将其放入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"))
});
}
}
}
1) Set AutoGenerateColumns to false 1)将AutoGenerateColumns设置为false
2) dgv.Columns["Item"].DataPropertyName = "Item"; 2)dgv.Columns [“Item”]。DataPropertyName =“Item”; dgv.Columns["Quantity"].DataPropertyName = "Quantity"; dgv.Columns [“Quantity”]。DataPropertyName =“Quantity”;
3) Then instead of select * from table1
use select item Item,quantity Quantity from table1
3)然后使用select item Item,quantity Quantity from table1
而不是select * from table1
select item Item,quantity Quantity from table1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.