Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fill DataGridView from SQLite DB (C#)

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;
        }
like image 270
John Avatar asked Mar 17 '15 18:03

John


1 Answers

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")) 
            });
        }
    }

}
like image 77
Abdul Saleem Avatar answered Sep 22 '22 21:09

Abdul Saleem