【问题标题】:Fill DataGridView from SQLite DB (C#)从 SQLite DB (C#) 填充 DataGridView
【发布时间】:2015-03-17 18:35:53
【问题描述】:

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

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

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

我的 SQLite DB,有一个包含三列的表(id PRIMARY KEY AUTO INCREMENT,item VARCHAR,quantity 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;
        }

【问题讨论】:

  • 你对 sqlite 使用什么参考?
  • 为此目的使用 SqlDatareader..
  • 我将如何使用它来完成这个特定的任务?
  • 告诉我你对 sqlite db 使用了什么参考。我会告诉你怎么做
  • 我不知道您所说的引用是什么意思:/ ...您的意思是我如何引用我的数据库?

标签: c# database sqlite datagridview


【解决方案1】:

如果您不想打扰列,可以使用 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")) 
            });
        }
    }

}

【讨论】:

    【解决方案2】:

    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

    【讨论】:

      猜你喜欢
      • 2012-03-14
      • 1970-01-01
      • 1970-01-01
      • 2020-06-01
      • 1970-01-01
      • 2011-03-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多