-
Use the
ComboBox.SelectedItem
Property to Get the Selected Value of a ComboBox inC#
-
Use
ComboBox.GetItemText
to Get Selected Value of a Combobox inC#
In this tutorial, you will learn the different methods to get the selected text and values of a ComboBox in C#. The most common method of getting a ComboBox control’s selected value is fetching it in a button click event using C#.
A ComboBox control in C# provides a combined functionality of a text box and a list box in a single control. The two primary methods to display and get the selected value of a ComboBox are using Combobox.SelectedItem
and ComboBox.GetItemText
properties in C#.
A selected item’s value can be retrieved using the SelectedValue
property. You can create a ComboBox
control using a Forms
designer at design-time or using the ComboBox
class in C# code at run-time.
Use the ComboBox.SelectedItem
Property to Get the Selected Value of a ComboBox in C#
In .NET’s ComboBox
control, the .SelectedItem
property displays a string representation of the selected value. The ComboBox.SelectedItem
property of a ComboBox in C# can get or set the currently selected item in a ComboBox.
The selected value of a ComboBox is null
initially and only be assigned after the user sets the SelectedItem
property to an object. When a user clicks on a value of a ComboBox, the value becomes the currently selected object/value in the list.
// its C# code of `Form1.cs` of `ComboboxSelectedvalue` project
using System;
using System.Windows.Forms;
namespace ComboboxSelectedvalue {
public partial class Form1 : Form {
public Form1() {
InitializeComponent();
}
// create a `comboBox1` ComboBox and `button1` button
// use the `button1` to get the selected value of the `comboBox1`
// it is a `button1` click event
private void button1_Click(object sender, EventArgs e) {
object b = comboBox1.SelectedItem;
string be = Convert.ToString(b);
MessageBox.Show("Your selected value is:" + be);
}
}
}
Use ComboBox.GetItemText
to Get Selected Value of a Combobox in C#
The this.comboBox1.GetItemText(value)
property of a ComboBox helps retrieve the displayed or selected value to a string variable. It’s extremely crucial for the selected item; however, there are times when it’s useful for the other values of a ComboBox.
The GetItemText
method of getting the selected value of a combo box is consistent with the definition of the existing SelectedValue
property and its implementation. It’ll return null
when the provided object doesn’t belong in the control’s list, and it’ll return the value itself if it’s valid and the ValueMember
is not set.
If you are unfamiliar, you can add a new class to your WinForms
project, add the following code, and then build your project to have a new control ready to be dragged onto a form.
// its C# code of `Form1.cs` of `ComboboxSelectedvalue` project
using System;
using System.Windows.Forms;
namespace ComboboxSelectedvalue {
public partial class Form1 : Form {
public Form1() {
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e) {
object b = comboBox1.SelectedItem;
object be = comboBox1.GetItemText(b);
MessageBox.Show("The value of your selected item is:" + be);
}
}
}
Create an instance of the ComboBox’s class, set its properties, and add a ComboBox
instance to the Form
controls to create a ComboBox
control at run-time. Either you can set control properties of a ComboBox at design time or from the Properties Window of the Visual Studio IDE.
The value of ComboBox.SelectedText
is empty at the start because the SelectedText
property gets and sets the selected text in a ComboBox only when it has focused on it. If the focus moves away, its value will be an empty string.
In this article, you have learned to get the selected value of a ComboBox in C# at design-time and run-time. After that, you have discovered various properties and methods of ComboBox
control in Windows Forms to get selected values.
Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe
In this article I will explain with an example, how to get Selected Text and Selected Value of ComboBox control in Windows Forms (WinForms) Application using C# and VB.Net.
The Selected Text and Selected Value of ComboBox control will be fetched in Button Click event in Windows Forms (WinForms) Application using C# and VB.Net.
Database
I have made use of the following table
Customers
with the schema as follows.
I have already inserted few records in the table.
Note: You can download the database table SQL by clicking the download link below.
Form Design
The Form consists of a ComboBox control and a Button. The Button has been assigned
Click
event handler.
Namespaces
You will need to import the following namespaces.
C#
using System.Data;
using System.Configuration;
using System.Data.SqlClient;
VB.Net
Imports System.Data
Imports System.Configuration
Imports System.Data.SqlClient
Bind (Populate) ComboBox from Database using DataTable (DataSet)
Inside the Form Load event, the records from the database are fetched into a DataTable.
Once the DataTable is populated from database, a new row is inserted in First position which will act as the Default (Blank) item for the ComboBox.
C#
private void Form1_Load(object sender, EventArgs e)
{
string constr = @»Data Source=.\SQL2014;Initial Catalog=AjaxSamples;Integrated Security=true»;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlDataAdapter sda = new SqlDataAdapter(«SELECT CustomerId, Name FROM Customers», con))
{
//Fill the DataTable with records from Table.
DataTable dt = new DataTable();
sda.Fill(dt);
//Insert the Default Item to DataTable.
DataRow row = dt.NewRow();
row[0] = 0;
row[1] = «Please select»;
dt.Rows.InsertAt(row, 0);
//Assign DataTable as DataSource.
cbCustomers.DataSource = dt;
cbCustomers.DisplayMember = «Name»;
cbCustomers.ValueMember = «CustomerId»;
}
}
}
VB.Net
Private Sub Form1_Load(ByVal sender As Object, ByVal e As EventArgs) Handles MyBase.Load
Dim constr As String = «Data Source=.\SQL2014;Initial Catalog=AjaxSamples;Integrated Security=true»
Using con As SqlConnection = New SqlConnection(constr)
Using sda As SqlDataAdapter = New SqlDataAdapter(«SELECT CustomerId, Name FROM Customers», con)
‘Fill the DataTable with records from Table.
Dim dt As DataTable = New DataTable()
sda.Fill(dt)
‘Insert the Default Item to DataTable.
Dim row As DataRow = dt.NewRow()
row(0) = 0
row(1) = «Please select»
dt.Rows.InsertAt(row, 0)
‘Assign DataTable as DataSource.
cbCustomers.DataSource = dt
cbCustomers.DisplayMember = «Name»
cbCustomers.ValueMember = «CustomerId»
End Using
End Using
End Sub
Fetching the selected Text and Value of ComboBox
When the Button is clicked, the Selected Text and Value of the ComboBox is fetched and displayed using
MessageBox
.
C#
private void btnSubmit_Click(object sender, EventArgs e)
{
string message = «Name: « + cbCustomers.Text;
message += Environment.NewLine;
message += «CustomerId: « + cbCustomers.SelectedValue;
MessageBox.Show(message);
}
VB.Net
Private Sub btnSubmit_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnSubmit.Click
Dim message As String = «Name: « & cbCustomers.Text
message += Environment.NewLine
message += «CustomerId: « & cbCustomers.SelectedValue
MessageBox.Show(message)
End Sub
Screenshot
Downloads
Реализация DI в PHP
Jason-Webb 13.05.2025
Когда я начинал писать свой первый крупный PHP-проект, моя архитектура напоминала запутаный клубок спагетти. Классы создавали другие классы внутри себя, зависимости жостко прописывались в коде, а о. . .
Обработка изображений в реальном времени на C# с OpenCV
stackOverflow 13.05.2025
Объединение библиотеки компьютерного зрения OpenCV с современным языком программирования C# создаёт симбиоз, который открывает доступ к впечатляющему набору возможностей. Ключевое преимущество этого. . .
POCO, ACE, Loki и другие продвинутые C++ библиотеки
NullReferenced 13.05.2025
В C++ разработки существует такое обилие библиотек, что порой кажется, будто ты заблудился в дремучем лесу. И среди этого многообразия POCO (Portable Components) – как маяк для тех, кто ищет. . .
Паттерны проектирования GoF на C#
UnmanagedCoder 13.05.2025
Вы наверняка сталкивались с ситуациями, когда код разрастается до неприличных размеров, а его поддержка становится настоящим испытанием. Именно в такие моменты на помощь приходят паттерны Gang of. . .
Создаем CLI приложение на Python с Prompt Toolkit
py-thonny 13.05.2025
Современные командные интерфейсы давно перестали быть черно-белыми текстовыми программами, которые многие помнят по старым операционным системам. CLI сегодня – это мощные, интуитивные и даже. . .
Конвейеры ETL с Apache Airflow и Python
AI_Generated 13.05.2025
ETL-конвейеры – это набор процессов, отвечающих за извлечение данных из различных источников (Extract), их преобразование в нужный формат (Transform) и загрузку в целевое хранилище (Load). . . .
Выполнение асинхронных задач в Python с asyncio
py-thonny 12.05.2025
Современный мир программирования похож на оживлённый мегаполис – тысячи процессов одновременно требуют внимания, ресурсов и времени. В этих джунглях операций возникают ситуации, когда программа. . .
Работа с gRPC сервисами на C#
UnmanagedCoder 12.05.2025
gRPC (Google Remote Procedure Call) — открытый высокопроизводительный RPC-фреймворк, изначально разработанный компанией Google. Он отличается от традиционых REST-сервисов как минимум тем, что. . .
CQRS (Command Query Responsibility Segregation) на Java
Javaican 12.05.2025
CQRS — Command Query Responsibility Segregation, или разделение ответственности команд и запросов. Суть этого архитектурного паттерна проста: операции чтения данных (запросы) отделяются от операций. . .
Шаблоны и приёмы реализации DDD на C#
stackOverflow 12.05.2025
Когда я впервые погрузился в мир Domain-Driven Design, мне показалось, что это очередная модная методология, которая скоро канет в лету. Однако годы практики убедили меня в обратном. DDD — не просто. . .
You currently have JavaScript disabled on your web browser.
This website uses JavaScript, and This web page needs JavaScript activated to work correctly.
Please active JavaScript on your web browser and then refresh this web page.
ComboBox
By Tim-Bo Tolbert, posted on Dec 26, 2021
The ComboBox control is found in the System.Windows.Forms
namespace within the System.Windows.Forms.dll
. In this blog post I am referring to the ComboBox control that is available in C# .NET-Core (.NET 6.0) with Visual Studio 2022 (although this code example might still work OK with older .NET versions).
The purpose and function of the ComboBox is to display a text box combined with a ListBox, which enables the user to select items from its drop down list or enter a new value into its text box.
You can change the way the ComboBox control looks on the form by altering the DropDownStyle property, so that its list is either always displayed or displayed in a drop-down. The DropDownStyle property also specifies whether the text portion is ReadOnly or if it can be edited. There is no setting to always display the list and disallow entering a new value (which is what a ListBox control is).
Items can be added or removed to the ComboBox control both at design time and at run time. You can assign an array of object references to add a group of items at once by using the AddRange method, which then displays the default string value for each object. You can add individual objects with the Add method. With the BeginUpdate and EndUpdate methods, you can add a large number of items without the control being repainted each time an item is added to the list. You can delete items with the Remove method, or you can clear all items from the entire list with the Clear method.
The ComboBox also provides features that enable you to efficiently add items and find text within the items of the list. The FindString and FindStringExact methods enable you to search for an item in the list that contains a specific search string.
Example Source Code
This example uses a ComboBox control, along with two Label controls and a TextBox control.
To add the ComboBox control to your form, you can double click on its name (i.e. ComboBox) as listed in the Toolbox window panel within the Form editor window. Alternatively, you can single click on it and then drag and drop it onto your form, to position it more closer to where you want it to be positioned at. Once it is added to the form then it will appear on the forms surface area having default ComboBox control values.
After you have added the ComboBox control to your form, then once you select it then you can view and edit that objects property values in the Properties window within the Forms editor window, where you can then change the controls Name, Items, and other properties as you desire.
In the following example, I added two Label objects to the Form, and then changed one of the Labels Text property to have a value of «Favorite Pet:» and the other Labels Text property to have a value of «Info:». I then added a ComboBox and positioned it be next to the first Label, and then added a TextBox and positioned it below the second Label. I adjusted the TextBox properties so that it is MultiLined, ReadOnly, and Scrollbars Visible:
From the Form editor, I select the control, view its Events properties in the Property Window, and then double clicked on the SelectedValueChanged and on the TextChanged events. Doing so automatically creates and links callback methods to that controls event into that forms .cs source code file, which I can then program some action to be performed whenever the user changes the value. In this example I use both events so that one captures when the user selects something from its drop down list and the other captures when the user manually types or pastes some value in. I then have both callback methods call and use the same function to process the selected item and then give some feedback to the user in the TextBox control:
namespace TestProgram
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
// add items to the combo box
comboBox1.Items.AddRange(new object[] {
"Cat",
"Dog",
"Bird",
"Fish"});
}
private void comboBox1_SelectedValueChanged(object sender, EventArgs e)
{
// the user selected a drop down value so process it
processSelection();
}
private void comboBox1_TextChanged(object sender, EventArgs e)
{
// the user manually entered a value so process it
processSelection();
}
// custom function to process the combobox text
private void processSelection()
{
// get the current text
string tempText = comboBox1.Text.Trim().ToLower();
// check if it is one of the items
if (tempText == "")
{
textBox1.Text = "";
}
else if (tempText == "cat")
{
textBox1.Text = "Cats are small carnivorous mammals. The scientific name for Cat is Felis catus.";
}
else if (tempText == "dog")
{
textBox1.Text = "Dogs are descendants of the wolf.";
}
else if (tempText == "bird")
{
textBox1.Text = "There are over 10,000 different species of birds around the world.";
}
else if (tempText == "fish")
{
textBox1.Text = "The whale shark is the largest fish, measuring over 18 meters in length.";
}
else
{
textBox1.Text = "Your favorite pet is a " + comboBox1.Text;
}
}
}
}
When you run the above examples and either select something from the ComboBox’s drop down list or type something into the ComboBox’s text box then you should see something similar to the following:
Final Thoughts
Thank you for reading, I hope you found this blog post (tutorial) educational and helpful.
This page has been viewed a total of 2571 times.