{"id":100,"date":"2022-08-02T07:43:25","date_gmt":"2022-08-02T07:43:25","guid":{"rendered":"https:\/\/noerguerra.com\/?p=100"},"modified":"2023-03-03T22:36:45","modified_gmt":"2023-03-03T22:36:45","slug":"how-to-build-a-temperature-converter-with-c-and-windows-forms","status":"publish","type":"post","link":"https:\/\/noerguerra.com\/blog\/how-to-build-a-temperature-converter-with-c-and-windows-forms\/","title":{"rendered":"How to build a temperature converter with C# and Windows Forms"},"content":{"rendered":"<p>In this tutorial, you&#8217;ll create a temperature converter application using C# and <strong>Windows Forms on Visual Studio<\/strong>.<\/p>\n<p>Windows Forms is a graphical framework used to create desktop applications that run on Windows. Since Visual Studio features a visual designer for it, it is possible to create a GUI for your application very easily using Forms.<\/p>\n<h2>What you will learn:<\/h2>\n<p>After following this tutorial, you will be able to:<\/p>\n<ul>\n<li>Build a basic Graphical User Interface (GUI) on Visual Studio.<\/li>\n<li>Code a program to perform conversions between different units.<\/li>\n<li>Understand how a program processes inputs through a GUI and how to display an output result to a user.<\/li>\n<\/ul>\n<h2>Create a new project<\/h2>\n<p>To start a new project, open <strong>Visual Studio 2022<\/strong>, and click on <em>Create a New Project<\/em> to continue.<br \/>\n<a href=\"https:\/\/noerguerra.com\/wp-content\/uploads\/2022\/08\/visual_studio_start_1.png\"><img decoding=\"async\" src=\"https:\/\/noerguerra.com\/wp-content\/uploads\/2022\/08\/visual_studio_start_1.png\" alt=\"\" \/><\/a><\/p>\n<p>On the next window, select <em>Windows Forms App<\/em> to create a new project that already includes the necessary structure to create a Windows Forms project. Then, click <em>Next<\/em>.<br \/>\n<a href=\"https:\/\/noerguerra.com\/wp-content\/uploads\/2022\/08\/create_new_project_1.png\"><img decoding=\"async\" src=\"https:\/\/noerguerra.com\/wp-content\/uploads\/2022\/08\/create_new_project_1.png\" alt=\"\" \/><\/a><\/p>\n<p>Configure your new project by naming it, and press <em>Next<\/em>.<br \/>\n<a href=\"https:\/\/noerguerra.com\/wp-content\/uploads\/2022\/08\/config_project.png\"><img decoding=\"async\" src=\"https:\/\/noerguerra.com\/wp-content\/uploads\/2022\/08\/config_project.png\" alt=\"\" \/><\/a><\/p>\n<p>Finally, click on <em>Create<\/em> to create the project.<br \/>\n<a href=\"https:\/\/noerguerra.com\/wp-content\/uploads\/2022\/08\/add_information.png\"><img decoding=\"async\" src=\"https:\/\/noerguerra.com\/wp-content\/uploads\/2022\/08\/add_information.png\" alt=\"\" \/><\/a><\/p>\n<h2>Design the GUI<\/h2>\n<p><strong>Event-driven programming<\/strong> is a programming paradigm where the flow of the program is determined by events. These events can be generated when the user interacts with the program by clicking on a button, writing on a textbox, checking a box, among others. After the event is generated, the program can respond by performing a certain action.<\/p>\n<p>The elements used to interact with the program are called <em>controls<\/em>, and Visual Studio provides you with multiple controls that you can add to your program with a <strong>drag-and-drop editor<\/strong>.<\/p>\n<p>After you&#8217;ve created the project, Visual Studio will show you an empty window, representing the GUI of your program.<br \/>\nOn the right side of the screen, you can see the <em>Solution Explorer<\/em>, where you can manage and open the different files that are part of this project. Under that panel, you&#8217;ll find the <em>Properties<\/em> panel, where you can change the properties of whatever element is currently selected on the Forms designer.<br \/>\n<a href=\"https:\/\/noerguerra.com\/wp-content\/uploads\/2022\/08\/drag_drop_designer.png\"><img decoding=\"async\" src=\"https:\/\/noerguerra.com\/wp-content\/uploads\/2022\/08\/drag_drop_designer.png\" alt=\"\" \/><\/a><\/p>\n<p>On the left sidebar, you can find a <em>Toolbox<\/em> to start adding elements to your form. Clicking on it will open a list with all the controls that you can add to your GUI. Click on <em>Common Controls<\/em> to display some of the most used elements when building Windows Forms.<br \/>\n<a href=\"https:\/\/noerguerra.com\/wp-content\/uploads\/2022\/08\/toolbox.png\"><img decoding=\"async\" src=\"https:\/\/noerguerra.com\/wp-content\/uploads\/2022\/08\/toolbox.png\" alt=\"Visual Studio 2022 Toolbox and Common controls\" \/><\/a><\/p>\n<p>Drag the Textbox controller from the Toolbox and drop it on the empty window in the designer.<br \/>\n<a href=\"https:\/\/noerguerra.com\/wp-content\/uploads\/2022\/08\/textbox_1.png\"><img decoding=\"async\" src=\"https:\/\/noerguerra.com\/wp-content\/uploads\/2022\/08\/textbox_1.png\" alt=\"\" \/><\/a><\/p>\n<p>Then, change its name on the <em>Properties<\/em> panel to <code>txtTempInput<\/code>.<br \/>\n<a href=\"https:\/\/noerguerra.com\/wp-content\/uploads\/2022\/08\/properties.png\"><img decoding=\"async\" src=\"https:\/\/noerguerra.com\/wp-content\/uploads\/2022\/08\/properties.png\" alt=\"\" \/><\/a><\/p>\n<p>Resize the window, and add the following controllers with their corresponding names:<br \/>\nCombobox -&gt; <code>cmbInputUnit<\/code><br \/>\nCombobox -&gt; <code>cmbOutputUnit<\/code><br \/>\nLabel -&gt; <code>label1<\/code><br \/>\nButton -&gt; <code>btnConvert<\/code><br \/>\nLabel -&gt; <code>lblResult<\/code><br \/>\n<a href=\"https:\/\/noerguerra.com\/wp-content\/uploads\/2022\/08\/form.png\"><img decoding=\"async\" src=\"https:\/\/noerguerra.com\/wp-content\/uploads\/2022\/08\/form.png\" alt=\"\" \/><\/a><\/p>\n<p>Click on the Button, and on the Properties panel find the <em>Text<\/em> field, and change it to <code>Convert.<\/code><br \/>\n<a href=\"https:\/\/noerguerra.com\/wp-content\/uploads\/2022\/08\/btn_rename.png\"><img decoding=\"async\" src=\"https:\/\/noerguerra.com\/wp-content\/uploads\/2022\/08\/btn_rename.png\" alt=\"\" \/><\/a><\/p>\n<p>Use the <em>Properties<\/em> panel to change the text of label1 to <code>To<\/code> as well as the title of the window to <code>Temp converter<\/code>, and <code>lblResult<\/code> to <code>0<\/code>.<\/p>\n<p>Finally, change the size of the font used on <code>lblResult<\/code> to 24 on the Properties panel.<\/p>\n<p>Your Form now should look similar to this:<br \/>\n<a href=\"https:\/\/noerguerra.com\/wp-content\/uploads\/2022\/08\/program_design-e1659350932219.png\"><img decoding=\"async\" src=\"https:\/\/noerguerra.com\/wp-content\/uploads\/2022\/08\/program_design-e1659350932219.png\" alt=\"\" \/><\/a><\/p>\n<h2>Code the conversion methods<\/h2>\n<p>Now you need to write the actual code that will perform the conversion between units. For this project, we will use the following formulas:<\/p>\n<p><strong>Fahrenheit to Celsius:<\/strong><br \/>\n<a href=\"https:\/\/noerguerra.com\/wp-content\/uploads\/2022\/07\/f_to_c.png\"><img decoding=\"async\" src=\"https:\/\/noerguerra.com\/wp-content\/uploads\/2022\/07\/f_to_c.png\" alt=\"Formula to convert from Fahrenheit to Celsius\" \/><\/a><\/p>\n<p>\u00b0C = (\u00b0F &#8211; 32) * 5\/9<\/p>\n<p><strong>Celsius to Fahrenheit:<\/strong><br \/>\n<a href=\"https:\/\/noerguerra.com\/wp-content\/uploads\/2022\/07\/c_to_f.png\"><img decoding=\"async\" src=\"https:\/\/noerguerra.com\/wp-content\/uploads\/2022\/07\/c_to_f.png\" alt=\"Formula to convert Celsius to Fahrenheit\" \/><\/a><\/p>\n<p>\u00b0F = (\u00b0C * 9\/5) + 32<\/p>\n<p><strong>Celsius to Kelvin:<\/strong><br \/>\n<a href=\"https:\/\/noerguerra.com\/wp-content\/uploads\/2022\/07\/c_to_k.png\"><img decoding=\"async\" src=\"https:\/\/noerguerra.com\/wp-content\/uploads\/2022\/07\/c_to_k.png\" alt=\"Formula to convert Celsius to Kelvin\" \/><\/a><\/p>\n<p>K = \u00b0C + 273.15<\/p>\n<p>Click on <em>Project&gt;Add Class<\/em> and name this new class <code>Convert.cs<\/code>.<\/p>\n<p>There, add the following method:<\/p>\n<pre><code class=\"language-csharp\">class Converter\n    {\n        public static double F_to_C(double F)\n        {\n            return (F - 32) * 5 \/ 9;\n        }\n    }<\/code><\/pre>\n<p>In the previous code:<\/p>\n<ul>\n<li>The method is <code>public<\/code> so that it can be accesed by other classes in the same namespace.<\/li>\n<li><code>F_to_C()<\/code> is also <code>static<\/code> since it doesn&#8217;t change any instance values within the class.<\/li>\n<li><code>F_to_C()<\/code> receives a parameter <code>double F<\/code>, which is the temperature to convert in F\u00b0, and returns the converted value as a <code>double<\/code>, since it&#8217;s common for temperature values to include decimal numbers.<\/li>\n<\/ul>\n<p>The rest of the conversion methods are very similar to this one:<\/p>\n<pre><code class=\"language-csharp\">class Converter\n    {\n        public static double F_to_C(double F)\n        {\n            return (F - 32) * 5 \/ 9;\n        }\n\n        public static double C_to_F(double C)\n        {\n            return (C * 9 \/ 5) + 32;\n        }\n\n        public static double C_to_K(double C)\n        {\n            return C + 273.15;\n        }\n\n        public static double K_to_C(double K)\n        {\n            return K - 273.15;\n        }\n\n        public static double K_to_F(double K)\n        {\n            var celsius = K_to_C(K);\n            var fahrenheit = C_to_F(celsius);\n            return fahrenheit;\n        }\n\n        public static double F_to_K(double F)\n        {\n            var celsius = F_to_C(F);\n            var kelvin = C_to_K(celsius);\n            return kelvin;\n        }\n    }<\/code><\/pre>\n<p>As you can see, these methods are very straightforward, only taking an input value and returning the result of the formula. Except for the last two, <code>K_to_F()<\/code> and <code>F_to_K()<\/code>, which call some of the previously defined methods to perform the conversion.<\/p>\n<h2>Process the user inputs and show the result<\/h2>\n<p>You have designed the User Interface of your program, and you have added the underlying functions that will process the data. Now it is time to connect those two parts of the program.<\/p>\n<p>Open the designer and double click on an empty part of your form. This will generate an empty <strong>event handler<\/strong> like the following:<\/p>\n<pre><code class=\"language-csharp\">private void Form1_Load(object sender, EventArgs e)\n        {\n\n        }<\/code><\/pre>\n<p>An event handler is a method used to monitor and process events. In this case, <code>Form1_Load()<\/code> will execute the code between the brackets when the form is first loaded.<\/p>\n<p>First of all, we are going to add the temperature units to the Combobox to let the user select them:<\/p>\n<pre><code class=\"language-csharp\">private void Form1_Load(object sender, EventArgs e)\n        {\n            String[] units = { &quot;\u00b0F&quot;, &quot;\u00b0C&quot;, &quot;K&quot; };\n            foreach (var unit in units)\n            {\n                cmbInputUnit.Items.Add(unit);\n                cmbOutputUnit.Items.Add(unit);\n            }\n\n            cmbInputUnit.Text = units[0];\n            cmbOutputUnit.Text = units[1];\n        }<\/code><\/pre>\n<p>In this code we:<\/p>\n<ul>\n<li>Declare an array of strings <code>units<\/code>, containing the three temperature units that the program can convert.<\/li>\n<li>Use a <code>foreach<\/code> loop to add each unit to <code>cmbInputUnit<\/code> and <code>cmbOutputUnit<\/code>. By using a loop we can avoid repetitive code.<\/li>\n<li>Set the initial value of <code>cmbInputUnit<\/code> to <code>\u00b0F<\/code> and <code>cmbOutputUnit<\/code> to <code>\u00b0C<\/code>.<\/li>\n<\/ul>\n<p>Now you only have to define the behavior of the <code>Convert<\/code> button. Go to the designer and double click on <code>btnConvert<\/code> to create an event handler for this control.<\/p>\n<pre><code class=\"language-csharp\">private void btnConvert_Click(object sender, EventArgs e)\n        {\n\n        }<\/code><\/pre>\n<p><code>btnConvert_Click()<\/code> will run immediately after the user clicks on <code>btnConvert<\/code>. In this method, we are going to read the number from <code>txtTempInput<\/code>, and perform the conversion based on <code>cmbInputUnit<\/code> and <code>cmbOutputUnit<\/code>. Finally, the resulting value will be shown on <code>lblResult<\/code>.<\/p>\n<pre><code class=\"language-csharp\">private void button1_Click(object sender, EventArgs e)\n        {\n            double value = Convert.ToDouble(txtTempInput.Text);\n            double result = 0;\n            string unit1 = cmbInputUnit.Text;\n            string unit2 = cmbOutputUnit.Text;\n\n            if (unit1 == unit2)\n            {\n                result = value;\n            }\n            else if (unit1 == &quot;\u00b0F&quot;)\n            {\n                if (unit2 == &quot;\u00b0C&quot;)\n                {\n                    result = Converter.F_to_C(value);\n                }\n                else if (unit2 == &quot;K&quot;)\n                {\n                    result = Converter.F_to_K(value);\n                }\n            }\n            else if (unit1 == &quot;\u00b0C&quot;)\n            {\n                if (unit2 == &quot;\u00b0F&quot;)\n                {\n                    result = Converter.C_to_F(value);\n                }\n                else if (unit2 == &quot;K&quot;)\n                {\n                    result = Converter.C_to_K(value);\n                }\n            }\n            else if (unit1 == &quot;K&quot;)\n            {\n                if (unit2 == &quot;\u00b0F&quot;)\n                {\n                    result = Converter.K_to_F(value);\n                }\n                else if (unit2 == &quot;\u00b0C&quot;)\n                {\n                    result = Converter.K_to_C(value);\n                }\n            }\n\n            result = Math.Round(result, 2);\n            lblResult.Text = $&quot;{result}{unit2}&quot;;\n        }<\/code><\/pre>\n<p>In the previous code, we:<\/p>\n<ul>\n<li>Convert the value from <code>txtTempInput<\/code> from <code>string<\/code> to <code>double<\/code>, and store it in <code>value<\/code>.<\/li>\n<li>Define <code>result<\/code> as a <code>double<\/code> to store the result of the conversion.<\/li>\n<li>Store the value from <code>cmbInputUnit<\/code> and <code>cmbInputUnit<\/code> in <code>unit1<\/code> and <code>unit2<\/code>, respectively. This will let us know what units we are converting, for example, \u00b0F to \u00b0C.<\/li>\n<li>Declare that if <code>unit1<\/code> is the same as <code>unit2<\/code>, the result is equal to the initial value entered by the user. In other words, no conversion is performed. Putting this at the top of the <code>if-else<\/code> statements helps us avoid unnecesary comparisons when no conversion is needed.<\/li>\n<li>Otherwise, we declare a series of <code>if-else<\/code> statements to catch every combination of <code>\u00b0F<\/code>, <code>\u00b0C<\/code>, and <code>K<\/code>, calling the respective methods that are defined in <code>Converter.cs<\/code>.<br \/>\nFor example, the first <code>else if<\/code> statement can be read as &quot;If the first temperature unit is Fahrenheit, and the second one is Celsius, convert the value from Fahrenheit to Celsius. Otherwise, convert to Kelvin.&quot;<\/li>\n<li>After the temperature value has been converted, call <code>Math.Round()<\/code> to round the resulting value down to 2 digits after the period.<\/li>\n<li>Change the text value of <code>lblResult<\/code> to display <code>result<\/code> followed by the output unit.<\/li>\n<\/ul>\n<p>Now you can proceed to test the program. If everything went well, you will see something like this:<br \/>\n<a href=\"https:\/\/noerguerra.com\/wp-content\/uploads\/2022\/08\/comparison.png\"><img decoding=\"async\" src=\"https:\/\/noerguerra.com\/wp-content\/uploads\/2022\/08\/comparison.png\" alt=\"\" \/><\/a><\/p>\n<h2>Conclusion<\/h2>\n<p>Coding a <strong>unit conversion program<\/strong> is a good exercise to advance your skills as a beginner in any language. Since it is not an excessively complex program, it allows you to focus on the structure of the language while building something that can be useful.<\/p>\n<p>While this is still a very simple program, there are many ways you could expand on it if you want to expand your knowledge on the development of desktop applications for Windows. For example:<\/p>\n<ul>\n<li>How would you avoid unexpected values from breaking the program? For example, if a user tries to convert <code>Q \u00b0F<\/code> to <code>K<\/code><\/li>\n<li>How could you prevent the user from entering unexpected values at all?<\/li>\n<li>The same problem is present on the Comboboxes. The user can still write any value instead of the predefined units. How can you force the user to select one of the predefined values?<\/li>\n<\/ul>\n<p>Another similar project that you could work on could be a currency converter, with the added complexity of keeping the program values updated by pulling the current values from the internet.<\/p>\n<p>At the end of the day, the only way to keep improving your skills is coding and challenging your knowledge.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>In this tutorial, you&#8217;ll create a temperature converter application using C# and Windows Forms on Visual Studio. Windows Forms is a graphical framework used to create desktop applications that run on Windows. Since Visual Studio features a visual designer for it, it is possible to create a GUI for your application very easily using Forms.&hellip; <a class=\"more-link\" href=\"https:\/\/noerguerra.com\/blog\/how-to-build-a-temperature-converter-with-c-and-windows-forms\/\">Continue reading <span class=\"screen-reader-text\">How to build a temperature converter with C# and Windows Forms<\/span><\/a><\/p>\n","protected":false},"author":1,"featured_media":143,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_monsterinsights_skip_tracking":false,"_monsterinsights_sitenote_active":false,"_monsterinsights_sitenote_note":"","_monsterinsights_sitenote_category":0,"footnotes":""},"categories":[10],"tags":[11],"class_list":["post-100","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-programming-tutorials","tag-c","entry"],"_links":{"self":[{"href":"https:\/\/noerguerra.com\/blog\/wp-json\/wp\/v2\/posts\/100","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/noerguerra.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/noerguerra.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/noerguerra.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/noerguerra.com\/blog\/wp-json\/wp\/v2\/comments?post=100"}],"version-history":[{"count":23,"href":"https:\/\/noerguerra.com\/blog\/wp-json\/wp\/v2\/posts\/100\/revisions"}],"predecessor-version":[{"id":295,"href":"https:\/\/noerguerra.com\/blog\/wp-json\/wp\/v2\/posts\/100\/revisions\/295"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/noerguerra.com\/blog\/wp-json\/wp\/v2\/media\/143"}],"wp:attachment":[{"href":"https:\/\/noerguerra.com\/blog\/wp-json\/wp\/v2\/media?parent=100"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/noerguerra.com\/blog\/wp-json\/wp\/v2\/categories?post=100"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/noerguerra.com\/blog\/wp-json\/wp\/v2\/tags?post=100"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}