从 SQLite 数据库填充 DataGridView (C#)

Fill DataGridView from SQLite DB (C#)

我正在尝试从 SQLite 数据库填充数据网格视图。

我发现有很多方法可以做到这一点。但是,我的 dgv(项目、数量)中有预先存在的列。

目前,当我将数据库加载到 dgv 时,我将数据库的列插入到 dgv 中,而不是将实际数据插入到正确的列中。

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

如何将数据库加载到 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;
        }

如果您不想打乱列,您可以使用 SQLiteDataReader 逐行读取并将其放入数据网格视图中..

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) 将 AutoGenerateColumns 设置为 false

2) dgv.Columns["Item"].DataPropertyName = "Item"; dgv.Columns["Quantity"].DataPropertyName = "Quantity";

3) 然后代替 select * from table1 采用 select item Item,quantity Quantity from table1