C++ Tutorial: Learn ComboBox Control in Visual C++
Submitted by Bright777 on Thursday, February 27, 2014 - 19:35.
In this tutorial we will talk about Combo Box control in Visual C++. Also we will make a simple program for basic arithmetical operations: addition, subtraction, multiplication and division.
First of all, let`s see what is Combo Box control. Combo Box control is little same to Text Edit, but it has one more option. You can add some constant values to be used in this control. While your program is running, you can choose one of your constant values and after that this value will be as the value of this control. It is really comfortable than you need to help user to choose option needed. For example in our program we will put in Combo Box control basic arithmetical operations.
Preparation
As you know, first you need to create a new Windows Forms Application project and then drag on main form these controls: one Combo Box, two Text Boxes, one Label and one Button. Situate them like on the picture:
After that add new values to the Combo Box control by clicking on Items property and you will see button with free dots – click on it and add each value in the separate line. Done.
Code
Then write the code below. This code shows what our program does then we click on button “Calculate”. In first lines we read values from Text Boxes, convert them to double and assign them to our variables. Then the program decides operation to perform and calculate the result. Also we have done the error catcher in the situation of division on zero.
Thanks
- private: System::Void button1_Click(System::Object^ sender, System::EventArgs^ e) {
- double a,b,output;
- a=Convert::ToDouble(textBox1->Text);
- b=Convert::ToDouble(textBox2->Text);
- if(comboBox1->Text=="+")
- {
- output=a+b;
- }
- if(comboBox1->Text=="-")
- {
- output=a-b;
- }
- if(comboBox1->Text=="/")
- {
- if(b!=0)
- output=a/b;
- else
- {
- MessageBox::Show("You can't divide on zero value!!!");
- return;
- }
- }
- if(comboBox1->Text=="*")
- {
- output=a*b;
- }
- label1->Text=" = "+Convert::ToString(output);
- }
Add new comment
- 1728 views