How to Fill Data with Two Display Member Based on ComboBox in C#
In this tutorial, I will teach you how to fill data with two display member based on combobox using c#. This method will illustrate how the two fields will link each other using the concatenation process. It also has the ability to display two fields in the combobox at the same time. This method is simple yet so helpful when you are dealing with combobox.
Step 1
Open Microsoft Visual Studio 2015 and create a new windows form application in C#.
Step 2
Do the form just like shown below.
Step 3
Press F7 to open the code editor. In the code editor, add a namespace for OLeDB
to access OLeDB
libraries.
using System.Data.OleDb;
Step 4
Create a connection between access database and c#. After that, declare all the classes that are needed.
OleDbConnection con = new OleDbConnection("Provider = Microsoft.ACE.OLEDB.12.0; Data Source =" + Application.StartupPath + "/studentdb.accdb"); OleDbCommand cmd; OleDbDataAdapter da; DataTable dt;
Step 5
Create a method for filling data in the combobox.
private void fill_data(string sql,ComboBox cbo) { try { con.Open(); cmd.Connection = con; cmd.CommandText = sql; da.SelectCommand = cmd; da.Fill(dt); cbo.DataSource = dt; cbo.DisplayMember = "Name"; cbo.ValueMember = "ID"; }catch(Exception ex) { MessageBox.Show(ex.Message); } finally { con.Close(); da.Dispose(); } }
Step 6
Do the following code to execute the method that you have created in the first load of the form.
private void Form1_Load(object sender, EventArgs e) { string sql; sql = "SELECT ID,(Fname + ' ' + Lname) as Name FROM tblstudent"; fill_data(sql, comboBox1); }
Download the complete sourcecode and run it on your computer.
For any questions about this article. You can contact me @
Email – [email protected]
Mobile No. – 09305235027 – TNT
Or feel free to comment below
- Add new comment
- 174 reads
Comments
Oelasor
Wed, 06/05/2019 - 11:03
Permalink
Alternative Tutorial Titles
An alternative title for the tutorial could be... "How to fill a combo box with items using the control's DataSource, DisplayMember and ValueMember properties". or "How to create a non-value-returning function that fills a combo box with data items". Anyways, your tutorial is good.
Lao Tzu - “Give a man a fish and you feed him for a day. Teach a man how to fish and you feed him for a lifetime.”
Oelasor
Add new comment