从 SQLite DB (C#) 填充 DataGridView [英] Fill DataGridView from SQLite DB (C#)

查看:26
本文介绍了从 SQLite DB (C#) 填充 DataGridView的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从 SQLite 数据库填充 datagridview.

I'm trying to fill a datagridview from an SQLite database.

我找到了很多方法来做到这一点.但是,我的 dgv(项目、数量)中有预先存在的列.

I've found plenty of ways of doing this. However, I have pre-existing columns in my dgv (Item, Quantity).

目前,当我将数据库加载到 dgv 时,我将数据库的列插入到 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.

我的 SQLite 数据库有一个包含三列的表(id PRIMARY KEY AUTO INCREMENT,项目 VARCHAR,数量 INTEGER).

My SQLite DB, has a table with three columns (id PRIMARY KEY AUTO INCREMENT, item VARCHAR, quantity INTEGER).

如何将 DB 加载到 dgv 的预先存在的列中?

How do load the DB into the pre-existing columns of the dgv?

填充 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;
        }

推荐答案

如果不想打扰列,可以使用 SQLiteDataReader 将行一一读取并放入 datagridview..

If you dont want to disturb the columns you can read the rows one by one using SQLiteDataReader and put it into 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 (C#) 填充 DataGridView的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆