Загрузка данных


namespace Mile_Kilometers // Имя проекта из методички
{
    partial class Form1
    {
        private System.ComponentModel.IContainer components = null;

        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Код, автоматически созданный конструктором форм Windows

        private void InitializeComponent()
        {
            this.textBox1 = new System.Windows.Forms.TextBox();
            this.label1 = new System.Windows.Forms.Label();
            this.label2 = new System.Windows.Forms.Label();
            this.button1 = new System.Windows.Forms.Button();
            this.SuspendLayout();
            // 
            // textBox1
            // 
            this.textBox1.Location = new System.Drawing.Point(84, 74);
            this.textBox1.Name = "textBox1";
            this.textBox1.Size = new System.Drawing.Size(156, 20);
            this.textBox1.TabIndex = 0;
            this.textBox1.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.textBox1_KeyPress);
            // 
            // label1
            // 
            this.label1.AutoSize = true;
            this.label1.Location = new System.Drawing.Point(36, 77);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(33, 13);
            this.label1.TabIndex = 1;
            this.label1.Text = "Мили";
            // 
            // label2
            // 
            this.label2.AutoSize = true;
            this.label2.Location = new System.Drawing.Point(36, 113);
            this.label2.Name = "label2";
            this.label2.Size = new System.Drawing.Size(35, 13);
            this.label2.TabIndex = 2;
            this.label2.Text = "label2";
            // 
            // button1
            // 
            this.button1.Location = new System.Drawing.Point(36, 157);
            this.button1.Name = "button1";
            this.button1.Size = new System.Drawing.Size(204, 48);
            this.button1.TabIndex = 3;
            this.button1.Text = "Вычислить";
            this.button1.UseVisualStyleBackColor = true;
            this.button1.Click += new System.EventHandler(this.button1_Click);
            // 
            // Form1
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(284, 261);
            this.Controls.Add(this.button1);
            this.Controls.Add(this.label2);
            this.Controls.Add(this.label1);
            this.Controls.Add(this.textBox1);
            
            // Свойства из задания:
            this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
            this.MaximizeBox = false;
            this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
            
            this.Name = "Form1";
            this.Text = "Мили-километры";
            this.Load += new System.EventHandler(this.Form1_Load);
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        #endregion

        private System.Windows.Forms.TextBox textBox1;
        private System.Windows.Forms.Label label1;
        private System.Windows.Forms.Label label2;
        private System.Windows.Forms.Button button1;
    }
}






using System;
using System.Windows.Forms;

namespace Mile_Kilometers // Имя проекта из методички
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        // Загрузка формы
        private void Form1_Load(object sender, EventArgs e)
        {
            textBox1.Clear();
            label2.Text = "";
        }

        // Обработка нажатия клавиш в TextBox (запрет на ввод букв)
        private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
        {
            // Если введена цифра или это управляющая клавиша (Backspace, Enter и т.д.) - разрешаем
            if ((e.KeyChar >= '0') && (e.KeyChar <= '9') || Char.IsControl(e.KeyChar))
            {
                return;
            }

            // Если введена точка - заменяем ее на запятую
            if (e.KeyChar == '.')
            {
                e.KeyChar = ',';
            }

            // Проверка на запятую (чтобы нельзя было ввести две запятые)
            if (e.KeyChar == ',')
            {
                if (textBox1.Text.IndexOf(',') == -1) // Если запятой еще нет
                {
                    return;
                }
                e.Handled = true; // Если запятая уже есть, блокируем ввод
            }
            else
            {
                // Блокируем все остальные символы (буквы и т.д.)
                e.Handled = true;
            }
        }

        // Обработка нажатия на кнопку "Вычислить"
        private void button1_Click(object sender, EventArgs e)
        {
            double mile;
            double km;
            try
            {
                // Пробуем перевести введенный текст в число
                mile = Convert.ToDouble(textBox1.Text);
                km = 1.609344 * mile; // Переводим мили в км
                
                // Записываем ответ в метку
                label2.Text = km.ToString() + " км.";
            }
            catch
            {
                // Если произошла ошибка (например, пустое поле), ставим курсор обратно в TextBox
                textBox1.Focus();
            }
        }
    }
}