C# - Populate ComboBox With SQLite

In this tutorial we will create a Populate ComboBox With SQLite using C#. C# is a general-purpose, object-oriented programming language. C# automatically manages inaccessible object memory using a garbage collector, which eliminates developer concerns and memory leaks. C# is faster than dynamically typed languages because things are more clearly defined. It contains several classes that support any C# platforms, like game development. It has a friendly environment for all new developers. So let's do the coding.

Getting Started

First you will have to download & install the Visual Studio. Visual Studios is an open source development feel free to create any application that you want. Here's the link for the Visual Studio https://www.visualstudio.com/. Here's the link for the SQLite Browser http://sqlitebrowser.org/.

Setting up SQLite

SQLite is very carefully tested prior to every release and relevant to use in some way. SQLite is very usable in any environments especially in embedded devices. First all you need to do is to install the components of the SQLIte database, by right clicking in the Main project title in the solution explorer then selecting the Manage NuGet Packages. tut1 Then go to the browse and search sqlite, after that install it and wait until the process is completed. tut2 Next go to the Updates and update the needed framework to make sqlite work properly. tut3 Note: Update only the framework if there is an available new update.

Application Design

We will now create the design for the application, first locate the designer file called form1.Designer.cs, this is the default name when you create a new windows form. Rename the form as Main.cs and then write these codes inside your designer file.
  1. namespace Populate_Combox_With_SQLite
  2. {
  3.     partial class Main
  4.     {
  5.         /// <summary>
  6.         /// Required designer variable.
  7.         /// </summary>
  8.         private System.ComponentModel.IContainer components = null;
  9.  
  10.         /// <summary>
  11.         /// Clean up any resources being used.
  12.         /// </summary>
  13.         /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
  14.         protected override void Dispose(bool disposing)
  15.         {
  16.             if (disposing && (components != null))
  17.             {
  18.                 components.Dispose();
  19.             }
  20.             base.Dispose(disposing);
  21.         }
  22.  
  23.         #region Windows Form Designer generated code
  24.  
  25.         /// <summary>
  26.         /// Required method for Designer support - do not modify
  27.         /// the contents of this method with the code editor.
  28.         /// </summary>
  29.         private void InitializeComponent()
  30.         {
  31.             this.label1 = new System.Windows.Forms.Label();
  32.             this.txt_name = new System.Windows.Forms.TextBox();
  33.             this.groupBox1 = new System.Windows.Forms.GroupBox();
  34.             this.rb_female = new System.Windows.Forms.RadioButton();
  35.             this.rb_male = new System.Windows.Forms.RadioButton();
  36.             this.label2 = new System.Windows.Forms.Label();
  37.             this.label3 = new System.Windows.Forms.Label();
  38.             this.comboBox1 = new System.Windows.Forms.ComboBox();
  39.             this.button1 = new System.Windows.Forms.Button();
  40.             this.groupBox1.SuspendLayout();
  41.             this.SuspendLayout();
  42.             //
  43.             // label1
  44.             //
  45.             this.label1.AutoSize = true;
  46.             this.label1.Font = new System.Drawing.Font("Arial", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
  47.             this.label1.Location = new System.Drawing.Point(64, 85);
  48.             this.label1.Name = "label1";
  49.             this.label1.Size = new System.Drawing.Size(86, 27);
  50.             this.label1.TabIndex = 0;
  51.             this.label1.Text = "NAME:";
  52.             //
  53.             // txt_name
  54.             //
  55.             this.txt_name.Font = new System.Drawing.Font("Arial", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
  56.             this.txt_name.Location = new System.Drawing.Point(156, 82);
  57.             this.txt_name.Name = "txt_name";
  58.             this.txt_name.Size = new System.Drawing.Size(347, 35);
  59.             this.txt_name.TabIndex = 1;
  60.             //
  61.             // groupBox1
  62.             //
  63.             this.groupBox1.Controls.Add(this.button1);
  64.             this.groupBox1.Controls.Add(this.comboBox1);
  65.             this.groupBox1.Controls.Add(this.label3);
  66.             this.groupBox1.Controls.Add(this.rb_female);
  67.             this.groupBox1.Controls.Add(this.rb_male);
  68.             this.groupBox1.Controls.Add(this.label2);
  69.             this.groupBox1.Controls.Add(this.label1);
  70.             this.groupBox1.Controls.Add(this.txt_name);
  71.             this.groupBox1.Font = new System.Drawing.Font("Arial", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
  72.             this.groupBox1.Location = new System.Drawing.Point(32, 12);
  73.             this.groupBox1.Name = "groupBox1";
  74.             this.groupBox1.Size = new System.Drawing.Size(588, 396);
  75.             this.groupBox1.TabIndex = 2;
  76.             this.groupBox1.TabStop = false;
  77.             this.groupBox1.Text = "BASIC INFORMATION";
  78.             //
  79.             // rb_female
  80.             //
  81.             this.rb_female.AutoSize = true;
  82.             this.rb_female.Location = new System.Drawing.Point(294, 160);
  83.             this.rb_female.Name = "rb_female";
  84.             this.rb_female.Size = new System.Drawing.Size(117, 31);
  85.             this.rb_female.TabIndex = 4;
  86.             this.rb_female.TabStop = true;
  87.             this.rb_female.Text = "Female";
  88.             this.rb_female.UseVisualStyleBackColor = true;
  89.             //
  90.             // rb_male
  91.             //
  92.             this.rb_male.AutoSize = true;
  93.             this.rb_male.Location = new System.Drawing.Point(184, 160);
  94.             this.rb_male.Name = "rb_male";
  95.             this.rb_male.Size = new System.Drawing.Size(88, 31);
  96.             this.rb_male.TabIndex = 3;
  97.             this.rb_male.TabStop = true;
  98.             this.rb_male.Text = "Male";
  99.             this.rb_male.UseVisualStyleBackColor = true;
  100.             //
  101.             // label2
  102.             //
  103.             this.label2.AutoSize = true;
  104.             this.label2.Font = new System.Drawing.Font("Arial", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
  105.             this.label2.Location = new System.Drawing.Point(29, 164);
  106.             this.label2.Name = "label2";
  107.             this.label2.Size = new System.Drawing.Size(121, 27);
  108.             this.label2.TabIndex = 2;
  109.             this.label2.Text = "GENDER:";
  110.             //
  111.             // label3
  112.             //
  113.             this.label3.AutoSize = true;
  114.             this.label3.Font = new System.Drawing.Font("Arial", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
  115.             this.label3.Location = new System.Drawing.Point(79, 240);
  116.             this.label3.Name = "label3";
  117.             this.label3.Size = new System.Drawing.Size(71, 27);
  118.             this.label3.TabIndex = 5;
  119.             this.label3.Text = "CITY:";
  120.             //
  121.             // comboBox1
  122.             //
  123.             this.comboBox1.FormattingEnabled = true;
  124.             this.comboBox1.Location = new System.Drawing.Point(156, 237);
  125.             this.comboBox1.Name = "comboBox1";
  126.             this.comboBox1.Size = new System.Drawing.Size(347, 35);
  127.             this.comboBox1.TabIndex = 6;
  128.             //
  129.             // button1
  130.             //
  131.             this.button1.Location = new System.Drawing.Point(191, 327);
  132.             this.button1.Name = "button1";
  133.             this.button1.Size = new System.Drawing.Size(220, 41);
  134.             this.button1.TabIndex = 7;
  135.             this.button1.Text = "SUBMIT";
  136.             this.button1.UseVisualStyleBackColor = true;
  137.             this.button1.Click += new System.EventHandler(this.Submit);
  138.             //
  139.             // Main
  140.             //
  141.             this.AutoScaleDimensions = new System.Drawing.SizeF(9F, 20F);
  142.             this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
  143.             this.ClientSize = new System.Drawing.Size(644, 434);
  144.             this.Controls.Add(this.groupBox1);
  145.             this.Name = "Main";
  146.             this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
  147.             this.Text = "Main";
  148.             this.Load += new System.EventHandler(this.Main_Load);
  149.             this.groupBox1.ResumeLayout(false);
  150.             this.groupBox1.PerformLayout();
  151.             this.ResumeLayout(false);
  152.  
  153.         }
  154.  
  155.         #endregion
  156.  
  157.         private System.Windows.Forms.Label label1;
  158.         private System.Windows.Forms.TextBox txt_name;
  159.         private System.Windows.Forms.GroupBox groupBox1;
  160.         private System.Windows.Forms.RadioButton rb_male;
  161.         private System.Windows.Forms.Label label2;
  162.         private System.Windows.Forms.RadioButton rb_female;
  163.         private System.Windows.Forms.ComboBox comboBox1;
  164.         private System.Windows.Forms.Label label3;
  165.         private System.Windows.Forms.Button button1;
  166.     }
  167. }
or also you create the layout by dragging the proper tools to the forms.

Creating the Script

We will now create the script to make things work. To do that go to the csharp script called Main.cs then right click and select view code, this will force you to go to the text editor. Then import these important modules inside the Class of the form.
  1. using System.Data.SQLite;
  2. using System.IO;
Next write these variable inside the Main class:
  1. SQLiteConnection conn;
  2. SQLiteCommand cmd;
  3. SQLiteDataReader dr;
  4. String connectString;
After that we need to create the database for the application, first write these blocks of codes.
  1. private void GenerateDatabase() {
  2.             String path = Application.StartupPath + @"\data.db";
  3.             if (!File.Exists(path)) {
  4.                 conn = new SQLiteConnection(connectString);
  5.                 conn.Open();
  6.                 String sql = "CREATE TABLE member (ID INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, gender TEXT, city TEXT)";
  7.                 cmd = new SQLiteCommand(sql, conn);
  8.                 cmd.ExecuteNonQuery();
  9.                 conn.Close();
  10.  
  11.                 GenerateCityTable();
  12.             }
  13.  
  14.         }
  15.  
  16.         private void GenerateCityTable() {
  17.             conn = new SQLiteConnection(connectString);
  18.             conn.Open();
  19.             String sql = "CREATE TABLE city (ID INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)";
  20.             cmd = new SQLiteCommand(sql, conn);
  21.             cmd.ExecuteNonQuery();
  22.             conn.Close();
  23.  
  24.             InserCity();
  25.         }
  26.  
  27.         private void InserCity() {
  28.             String[] city = CityList();
  29.  
  30.             try
  31.             {
  32.                 conn = new SQLiteConnection(connectString);
  33.                 cmd = new SQLiteCommand();
  34.                 cmd.CommandText = @"INSERT INTO city (name) VALUES(@name)";
  35.                 cmd.Connection = conn;
  36.  
  37.                 cmd.Parameters.Add(new SQLiteParameter("@name", DbType.String));
  38.                 conn.Open();
  39.  
  40.                 foreach (String list in city) {
  41.                     cmd.Parameters[0].Value = list;
  42.  
  43.                     cmd.ExecuteNonQuery();
  44.                 }
  45.  
  46.                 conn.Close();
  47.             }
  48.             catch (Exception ex)
  49.             {
  50.                 MessageBox.Show(ex.Message);
  51.             }
  52.         }
  53.  
  54.         private String[] CityList() {
  55.             String[] city = {
  56.                 "New York",
  57.                 "Los Angeles",
  58.                 "Chicago",
  59.                 "Houston",
  60.                 "Philadelphia",
  61.                 "Phoenix",
  62.                 "San Antonio",
  63.                 "San Diego"
  64.             };
  65.  
  66.             return city;
  67.         }
Then initialize the methods inside the Main method.
  1.  public Main()
  2.         {
  3.             InitializeComponent();
  4.             connectString = @"Data Source=" + Application.StartupPath + @"\data.db;version=3";
  5.             GenerateDatabase();
  6.         }
To populate the ComboBox, double click the form to automatically create a Form Load method, And then write these codes inside of it to retrieve the data from the database.
  1. try
  2.             {
  3.                 conn = new SQLiteConnection(connectString);
  4.                 cmd = new SQLiteCommand();
  5.                 cmd.CommandText = @"SELECT * FROM city ORDER BY name ASC";
  6.                 cmd.Connection = conn;
  7.                 conn.Open();
  8.                 dr = cmd.ExecuteReader();
  9.                 while (dr.Read()) {
  10.                     comboBox1.Items.Add(dr["name"]);
  11.                 }
  12.  
  13.                 dr.Close();
  14.                 conn.Close();
  15.  
  16.             }
  17.             catch(Exception ex) {
  18.                 MessageBox.Show(ex.Message);
  19.             }
Lastly, to save the data to the database we will create a script to make it happen. All you have to do is just write down these codes inside the Submit method from the Event of the button.
  1. private void Submit(object sender, EventArgs e) {
  2.  
  3.             String gender = "";
  4.  
  5.             if (rb_male.Checked)
  6.             {
  7.                 gender = "Male";
  8.             }
  9.             else if (rb_female.Checked)
  10.             {
  11.                 gender = "Female";
  12.             }
  13.  
  14.  
  15.             if (txt_name.Text == "" || gender == "" || comboBox1.Text == "")
  16.             {
  17.                 MessageBox.Show("Required Fields!");
  18.             }
  19.             else {
  20.                 try
  21.                 {
  22.                     conn = new SQLiteConnection(connectString);
  23.                     cmd = new SQLiteCommand();
  24.                     cmd.CommandText = @"INSERT INTO member (name, gender, city) VALUES(@name, @gender, @city)";
  25.                     cmd.Connection = conn;
  26.                     cmd.Parameters.Add(new SQLiteParameter("@name", txt_name.Text));
  27.                     cmd.Parameters.Add(new SQLiteParameter("@gender", gender));
  28.                     cmd.Parameters.Add(new SQLiteParameter("@city", comboBox1.Text));
  29.                     conn.Open();
  30.  
  31.                     int i = cmd.ExecuteNonQuery();
  32.  
  33.                     if (i == 1)
  34.                     {
  35.                         MessageBox.Show("Successfully Created!");
  36.                         txt_name.Text = "";
  37.                         gender = "";
  38.                         comboBox1.Text = "";
  39.                         rb_male.Checked = false;
  40.                         rb_female.Checked = false;
  41.                     }
  42.  
  43.                     conn.Close();
  44.                 }
  45.                 catch (Exception ex)
  46.                 {
  47.                     MessageBox.Show(ex.Message);
  48.                 }
  49.             }
  50.         }
Try to run the application and see if it works. There you go we successfully created a Populate ComboBox With SQLite using C#. I hope that this tutorial help you understand on how to develop an application using C#. For more updates and tutorials just kindly visit this site. Enjoy Coding!!!

Add new comment