Back to Top

Writing Custom Windows Forms Code


It's time to write some C# code! But first, let us imagine how our application will work. We need to enter the "Amount" and "Tax (%)" values, and then press the "Compute" button. The program will compute the tax, and then display it in the "Sales Tax" field.


But how do we compute the tax in the first place? First, we must divide the amount by 1 + Tax (%). If the tax is 5% we must divide the sum by 1.05, if the tax is 12% we must divide the sum by 1.12, and so on.


Therefore, our math formula has to look like this:


Sales Tax = Amount - Amount / (1 + Sales Tax/100)


The C# code will look a bit different, of course, but that's what we will use as a base for it.


Our program will begin by reading the value that's input in the "Text" property of "AmountBox" - in other words, "AmountBox.Text". We don't want to read the "Amount" text, because we've only used that component as a label, remember?


However, the "Text" property assumes that we will use that control to input strings such as "Mary" or "x32Qdgh1" in the TextBox field. Fortunately, we can convert those texts to numbers easily, by making use of a line of code that looks like this:


float.Parse(AmountBox.Text);


The "Parse" method will turn our "1234" text into a "1234" number, get it? We will need to store that number in a variable (a dedicated computer memory space); let's call if amountNumber. So, it means that one of our C# lines of code should look like this:


amountNumber = float.Parse(AmountBox.Text);


We must use "float" variables because the amount may not be an integer. Now that we've got these things sorted out, let's repeat the process for "Tax (%) value", which must store the numerical value that's input into "TaxBox.Text".


taxNumber = float.Parse(TaxBox.Text);


Well, we have got everything we need to compute our resultNumber:


resultNumber = amountNumber - amountNumber / (1 + taxNumber/100);


Take a look at our math formula at the beginning of the article and you will see that it is quite similar with this one.


And let's see the entire source code for our fully functional program:


full programI know that the source file may look a bit intimidating, but I promise to explain everything. For now, double click the button on the form to open its event handler, and then type in the code above. If you make a mistake, Visual Studio will highlight the error at the bottom of the screen. Double click the error message to see which line of code has problems.


errorSave the project, click the green "Play" button, and then type in some values to see how it works. Here's how it runs on my end.


program runningThat's all for now! Stay tuned for the next tutorial, when we will study the code that's been used for our tax calculator application.