C# - Populate ComboBox With SQLite
Submitted by razormist on Friday, April 27, 2018 - 20:32.
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.
or also you create the layout by dragging the proper tools to the forms.
Next write these variable inside the Main class:
After that we need to create the database for the application, first write these blocks of codes.
Then initialize the methods inside the Main method.
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.
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.
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!!!
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. Then go to the browse and search sqlite, after that install it and wait until the process is completed. Next go to the Updates and update the needed framework to make sqlite work properly. 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.- namespace Populate_Combox_With_SQLite
- {
- partial class Main
- {
- /// <summary>
- /// Required designer variable.
- /// </summary>
- private System.ComponentModel.IContainer components = null;
- /// <summary>
- /// Clean up any resources being used.
- /// </summary>
- /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
- protected override void Dispose(bool disposing)
- {
- if (disposing && (components != null))
- {
- components.Dispose();
- }
- base.Dispose(disposing);
- }
- #region Windows Form Designer generated code
- /// <summary>
- /// Required method for Designer support - do not modify
- /// the contents of this method with the code editor.
- /// </summary>
- private void InitializeComponent()
- {
- this.groupBox1.SuspendLayout();
- this.SuspendLayout();
- //
- // label1
- //
- this.label1.AutoSize = true;
- this.label1.Font = new System.Drawing.Font("Arial", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
- this.label1.Name = "label1";
- this.label1.TabIndex = 0;
- this.label1.Text = "NAME:";
- //
- // txt_name
- //
- this.txt_name.Font = new System.Drawing.Font("Arial", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
- this.txt_name.Name = "txt_name";
- this.txt_name.TabIndex = 1;
- //
- // groupBox1
- //
- this.groupBox1.Controls.Add(this.button1);
- this.groupBox1.Controls.Add(this.comboBox1);
- this.groupBox1.Controls.Add(this.label3);
- this.groupBox1.Controls.Add(this.rb_female);
- this.groupBox1.Controls.Add(this.rb_male);
- this.groupBox1.Controls.Add(this.label2);
- this.groupBox1.Controls.Add(this.label1);
- this.groupBox1.Controls.Add(this.txt_name);
- this.groupBox1.Font = new System.Drawing.Font("Arial", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
- this.groupBox1.Name = "groupBox1";
- this.groupBox1.TabIndex = 2;
- this.groupBox1.TabStop = false;
- this.groupBox1.Text = "BASIC INFORMATION";
- //
- // rb_female
- //
- this.rb_female.AutoSize = true;
- this.rb_female.Name = "rb_female";
- this.rb_female.TabIndex = 4;
- this.rb_female.TabStop = true;
- this.rb_female.Text = "Female";
- this.rb_female.UseVisualStyleBackColor = true;
- //
- // rb_male
- //
- this.rb_male.AutoSize = true;
- this.rb_male.Name = "rb_male";
- this.rb_male.TabIndex = 3;
- this.rb_male.TabStop = true;
- this.rb_male.Text = "Male";
- this.rb_male.UseVisualStyleBackColor = true;
- //
- // label2
- //
- this.label2.AutoSize = true;
- this.label2.Font = new System.Drawing.Font("Arial", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
- this.label2.Name = "label2";
- this.label2.TabIndex = 2;
- this.label2.Text = "GENDER:";
- //
- // label3
- //
- this.label3.AutoSize = true;
- this.label3.Font = new System.Drawing.Font("Arial", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
- this.label3.Name = "label3";
- this.label3.TabIndex = 5;
- this.label3.Text = "CITY:";
- //
- // comboBox1
- //
- this.comboBox1.FormattingEnabled = true;
- this.comboBox1.Name = "comboBox1";
- this.comboBox1.TabIndex = 6;
- //
- // button1
- //
- this.button1.Name = "button1";
- this.button1.TabIndex = 7;
- this.button1.Text = "SUBMIT";
- this.button1.UseVisualStyleBackColor = true;
- //
- // Main
- //
- this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
- this.Controls.Add(this.groupBox1);
- this.Name = "Main";
- this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
- this.Text = "Main";
- this.groupBox1.ResumeLayout(false);
- this.groupBox1.PerformLayout();
- this.ResumeLayout(false);
- }
- #endregion
- private System.Windows.Forms.Label label1;
- private System.Windows.Forms.TextBox txt_name;
- private System.Windows.Forms.GroupBox groupBox1;
- private System.Windows.Forms.RadioButton rb_male;
- private System.Windows.Forms.Label label2;
- private System.Windows.Forms.RadioButton rb_female;
- private System.Windows.Forms.ComboBox comboBox1;
- private System.Windows.Forms.Label label3;
- private System.Windows.Forms.Button button1;
- }
- }
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.- using System.Data.SQLite;
- using System.IO;
- SQLiteConnection conn;
- SQLiteCommand cmd;
- SQLiteDataReader dr;
- String connectString;
- private void GenerateDatabase() {
- String path = Application.StartupPath + @"\data.db";
- if (!File.Exists(path)) {
- conn.Open();
- String sql = "CREATE TABLE member (ID INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, gender TEXT, city TEXT)";
- cmd.ExecuteNonQuery();
- conn.Close();
- GenerateCityTable();
- }
- }
- private void GenerateCityTable() {
- conn.Open();
- String sql = "CREATE TABLE city (ID INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)";
- cmd.ExecuteNonQuery();
- conn.Close();
- InserCity();
- }
- private void InserCity() {
- String[] city = CityList();
- try
- {
- cmd.CommandText = @"INSERT INTO city (name) VALUES(@name)";
- cmd.Connection = conn;
- conn.Open();
- foreach (String list in city) {
- cmd.Parameters[0].Value = list;
- cmd.ExecuteNonQuery();
- }
- conn.Close();
- }
- catch (Exception ex)
- {
- MessageBox.Show(ex.Message);
- }
- }
- private String[] CityList() {
- String[] city = {
- "New York",
- "Los Angeles",
- "Chicago",
- "Houston",
- "Philadelphia",
- "Phoenix",
- "San Antonio",
- "San Diego"
- };
- return city;
- }
- public Main()
- {
- InitializeComponent();
- connectString = @"Data Source=" + Application.StartupPath + @"\data.db;version=3";
- GenerateDatabase();
- }
- try
- {
- cmd.CommandText = @"SELECT * FROM city ORDER BY name ASC";
- cmd.Connection = conn;
- conn.Open();
- dr = cmd.ExecuteReader();
- while (dr.Read()) {
- comboBox1.Items.Add(dr["name"]);
- }
- dr.Close();
- conn.Close();
- }
- catch(Exception ex) {
- MessageBox.Show(ex.Message);
- }
- private void Submit(object sender, EventArgs e) {
- String gender = "";
- {
- gender = "Male";
- }
- {
- gender = "Female";
- }
- if (txt_name.Text == "" || gender == "" || comboBox1.Text == "")
- {
- MessageBox.Show("Required Fields!");
- }
- else {
- try
- {
- cmd.CommandText = @"INSERT INTO member (name, gender, city) VALUES(@name, @gender, @city)";
- cmd.Connection = conn;
- conn.Open();
- int i = cmd.ExecuteNonQuery();
- if (i == 1)
- {
- MessageBox.Show("Successfully Created!");
- txt_name.Text = "";
- gender = "";
- comboBox1.Text = "";
- }
- conn.Close();
- }
- catch (Exception ex)
- {
- MessageBox.Show(ex.Message);
- }
- }
- }
Add new comment
- 2145 views