Lektion 18: lösningsförslag

  1. // 1
  2. class MyForm : Form
  3. {
  4. private NumericUpDown temperatureBox;
  5. private NumericUpDown volumeBox;
  6. public MyForm()
  7. {
  8. TableLayoutPanel table = new TableLayoutPanel
  9. {
  10. RowCount = 3,
  11. ColumnCount = 2,
  12. Dock = DockStyle.Fill
  13. };
  14. Controls.Add(table);
  15. Label temperatureLabel = new Label
  16. {
  17. Text = "Temperature"
  18. };
  19. table.Controls.Add(temperatureLabel);
  20. temperatureBox = new NumericUpDown();
  21. table.Controls.Add(temperatureBox);
  22. Label volumeLabel = new Label
  23. {
  24. Text = "Volume"
  25. };
  26. table.Controls.Add(volumeLabel);
  27. volumeBox = new NumericUpDown();
  28. table.Controls.Add(volumeBox);
  29. Button button = new Button
  30. {
  31. Text = "Is This Habitable?",
  32. Dock = DockStyle.Fill
  33. };
  34. table.SetColumnSpan(button, 2);
  35. table.Controls.Add(button);
  36. button.Click += ClickedEventHandler;
  37. }
  38. private void ClickedEventHandler(object sender, EventArgs e)
  39. {
  40. double temperature = (double) temperatureBox.Value;
  41. double volume = (double) volumeBox.Value;
  42. bool isHabitable = temperature >= 18 && temperature <= 26 && volume <= 45;
  43. MessageBox.Show("Is Habitable: " + isHabitable);
  44. }
  45. }
  46. // 2
  47. class MyForm : Form
  48. {
  49. public MyForm()
  50. {
  51. TableLayoutPanel table = new TableLayoutPanel
  52. {
  53. RowCount = 5,
  54. ColumnCount = 5,
  55. Dock = DockStyle.Fill
  56. };
  57. Controls.Add(table);
  58. for (int i = 1; i <= 25; i += 1)
  59. {
  60. Button button = new Button
  61. {
  62. Text = "Button " + i
  63. };
  64. table.Controls.Add(button);
  65. button.Click += ClickedEventHandler;
  66. }
  67. }
  68. private void ClickedEventHandler(object sender, EventArgs e)
  69. {
  70. Button button = (Button) sender;
  71. MessageBox.Show("You clicked: " + button.Text);
  72. }
  73. }