How to Get the ValueMember of a ComboBox in C# and MySQL Database
Submitted by janobe on Friday, March 29, 2019 - 15:49.
In this tutorial, I will teach you how to get a valuemember of a combobox using C# and MySQL database. This method has the capability to get ID of the name of person inside a dropdown selection and it would be displayed inside a listbox . This simple manipulation of data will help you when you are dealing with combobox. Lets begin.
The complete source code is included you can download it 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.
Creating Application
Step 1
Open Microsoft Visual Studio 2015 and create a new windows form application for c#.
Step 2
Do the form just like shown below.
Step 3
Open the code editor by pressing the F7 on your keyboard. In the code editor, add a namespace to accessMySQL
libraries
- using MySql.Data.MySqlClient;
Step 4
Create a connection between C# and MySQL database. After that, declare all the classes and a string variable that is needed.- MySqlConnection con = new MySqlConnection("server=localhost;user id=root;password=;database=dbsubjects;sslMode=none");
- MySqlCommand cmd;
- MySqlDataAdapter da;
- DataTable dt;
- String sql;
Step 5
Create a method to fill the data in a 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 = "fname";
- cbo.ValueMember ="idno";
- cbo.Text = "Select";
- }catch(Exception ex)
- {
- MessageBox.Show(ex.ToString());
- }
- finally
- {
- con.Close();
- da.Dispose();
- }
- }
Step 6
Write the following codes to clear the listbox and fill the data in a combobox in the first load of the form.- private void Form1_Load(object sender, EventArgs e)
- {
- sql = "SELECT * FROM `tblstudent`";
- fill_data(sql, comboBox1);
- listBox1.Items.Clear();
- }
Step 7
Double click a combobox and add the following codes to add and display a valuemember of a combobox inside the listbox.- private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
- {
- listBox1.Items.Clear();
- listBox1.Items.Add(comboBox1.SelectedValue.ToString());
- }
Add new comment
- 1791 views