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.
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
= new OleDbCommand
();
da
= new OleDbDataAdapter
();
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