Nick_F
Nick_F

Reputation: 1121

SQLite - storing the column names of a table in a list of strings

I don't know how to store the column names from a SQLite table into a list of strings. The following code fills a dataGridView with the column names (amongst other things):

string sDatabasePath = DBPath();
SQLiteConnectionStringBuilder datasource = new SQLiteConnectionStringBuilder();
datasource.Add("Data Source", sDatabasePath);
datasource.Add("Version", "3");
datasource.Add("New", "False");
datasource.Add("Compress", "True");             
using (SQLiteConnection connection = new SQLiteConnection(datasource.ConnectionString))
{
    connection.Open(); //opens connection
    SQLiteCommand getColumnNames = new SQLiteCommand("PRAGMA table_info('myTable');", connection);
    SQLiteDataAdapter myAdapter = new SQLiteDataAdapter(getColumnNames);
    DataSet myDataSet = new DataSet();
    //myAdapter.Fill(myDataSet, "name");
    this.dataGridView1.DataSource = myDataSet;
    this.dataGridView1.DataMember = "name";
    connection.Close();
}

Upvotes: 0

Views: 3809

Answers (2)

James
James

Reputation: 82096

If you are looking to bind your query to a list and not a DataGridView, then you should use a data reader and not a data set e.g.

using (SQLiteConnection connection = new SQLiteConnection(datasource.ConnectionString))
using (SQLiteCommand cmd = new SQLiteCommand("PRAGMA table_info('myTable');"))
{
    connection.Open(); //opens connection
    var tableNames = new List<string>();
    using (SQLiteDataReader reader = cmd.ExecuteReader())
    {
        while (reader.Read())
        {
            tableNames.Add(reader.GetString(0)); // read 'name' column
        }
    }
    return tableNames;
}

Upvotes: 1

Dietrich Prg
Dietrich Prg

Reputation: 84

            DataTable dtb = new DataTable();
            myAdapter.Fill(dtb);

            string[] names = new string[dtb.Rows.Count];
            for (int i = 0; i < dtb.Rows.Count; i++)
            {
                DataRow row = dtb.Rows[i];
                names[i] = row[0].ToString();
            }

Upvotes: 1

Related Questions