
But first, let's understand one important design concept, the TableLayoutPanel control.
We are used to display informations using labels, but we also found out the limitations of this control. With labels, it is very difficult to predict the display of the string or text being output. For example, a label might contain multiple lines of text (we might use '\n' for new lines, or '\t' for tabs).
With TableLayoutPanel, the organisation of any controls including labels, is made easier.
The TableLayoutPanel is just a series of rows and columns, analogous to a table.
One of the main advantage of using the TableLayoutPanel is that you can refer to each control in a cell, just like an array. An array of controls, found in the Table. We will use that concept in this code.
For example, you might want to contain a list of Coins you have, and the number of coins, each represented on a different row, with separate columns for each category. You can do it with labels only, but the best design solution is to use the TableLayoutPanel with labels.
In this scenario, Coins are on the top row, whereas the numbers are below the respective coins, bottom row. We create the table TableLayoutPanel1.
In design view, the table is set as follows, with 4 normal labels, one in each cell.
Now the nice part. You can actually refer to the labels in an 'array-like' fashion. For example,
So this is why we should be using arrays and loops in this question.TableLayoutPanel1.Controls[0] will refer to label2.TableLayoutPanel1.Controls[1] will refer to label3.TableLayoutPanel1.Controls[2] will refer to label4.TableLayoutPanel1.Controls[3] will refer to label5.
This is the end of the explanation on why we should use the TableLayoutPanel control.
This is the final code for the home work.
1: int[] coins = { 50, 20, 10, 5 };
2: int[] numbers = { 0, 0, 0, 0 };
3: int iAmount = int.Parse(txtAmount.Text);
4: int iCoinsNum = 0; //stores the number of coins used
5:
6: iAmount %= 100; //Get the 2 last digits
7:
8: for (int i = 0; i < coins.Length; i++)
9: {
10: numbers[i] = iAmount / coins[i]; //gets the number of particular coin in amount
11: iAmount = iAmount % coins[i]; //gets the remainder
12: tableLayoutPanel1.Controls[i].Text = coins[i] + " cent \n" + numbers[i];
13: //display the coins value and amount, in each label per column in the TableLayoutPanel
14: iCoinsNum += numbers[i]; //accumulates the amount of coins
15: }
16:
17: if (iCoinsNum == 0) //check if any coin was required
18: {
19: btnReset_Click(sender, e);
20: lblCoinsNum.Text = "No coins required.";
21: }
22: else
23: {
24: lblCoinsNum.Text = "" + iCoinsNum + " coins required.";
25: }
Note: The order of the Coins array is important, as you want to divide the 50c coins first before moving to the 20c coins, and so on.
No comments:
Post a Comment