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


using System;
using System.Drawing;
using System.Windows.Forms;

namespace lr16
{
    public partial class Form1 : Form
    {
        private ComboBox cbA, cbB, cbC;
        private TextBox tbX, tbY, tbZ;
        private RadioButton rbMethod1, rbMethod2;
        private CheckBox cbIncludeZ;
        private Button btnCalculate, btnClear;
        private Label lblResult, lblMethodInfo;
        private ListBox lbHistory;

        public Form1()
        {
            InitializeComponent();
            LoadData();                    // ← Важно: заполняем данные после создания элементов
        }

        private void InitializeComponent()
        {
            this.Size = new Size(820, 720);
            this.Text = "Лабораторная работа №16 — Вариант 10";
            this.StartPosition = FormStartPosition.CenterScreen;
            this.BackColor = Color.WhiteSmoke;

            // Заголовок
            var title = new Label
            {
                Text = "Лабораторная работа №16\nМеханизм событий. Простые элементы управления\nВариант 10",
                Font = new Font("Segoe UI", 15, FontStyle.Bold),
                Location = new Point(20, 15),
                Size = new Size(780, 80),
                TextAlign = ContentAlignment.MiddleCenter,
                ForeColor = Color.DarkBlue
            };
            this.Controls.Add(title);

            // Способ расчёта
            var gbMethod = new GroupBox { Text = "Способ расчёта", Location = new Point(30, 110), Size = new Size(750, 120) };
            lblMethodInfo = new Label { Text = "Выбран способ: Прямое вычисление", Location = new Point(20, 25), Size = new Size(600, 25) };

            rbMethod1 = new RadioButton { Text = "Способ 1: Прямое вычисление  W = a·x + b·y + c·z", Location = new Point(20, 55), AutoSize = true, Checked = true };
            rbMethod1.CheckedChanged += (s, e) => { if (rbMethod1.Checked) lblMethodInfo.Text = "Выбран способ: Прямое вычисление"; };

            rbMethod2 = new RadioButton { Text = "Способ 2: Через массив коэффициентов и цикл for", Location = new Point(20, 80), AutoSize = true };
            rbMethod2.CheckedChanged += (s, e) => { if (rbMethod2.Checked) lblMethodInfo.Text = "Выбран способ: Через массив и цикл"; };

            gbMethod.Controls.Add(lblMethodInfo);
            gbMethod.Controls.Add(rbMethod1);
            gbMethod.Controls.Add(rbMethod2);
            this.Controls.Add(gbMethod);

            // Коэффициенты
            var gbCoeff = new GroupBox { Text = "Коэффициенты a, b, c", Location = new Point(30, 245), Size = new Size(380, 170) };

            cbA = new ComboBox { Location = new Point(100, 35), Width = 170, DropDownStyle = ComboBoxStyle.DropDownList };
            cbB = new ComboBox { Location = new Point(100, 70), Width = 170, DropDownStyle = ComboBoxStyle.DropDownList };
            cbC = new ComboBox { Location = new Point(100, 105), Width = 170, DropDownStyle = ComboBoxStyle.DropDownList };

            gbCoeff.Controls.Add(new Label { Text = "a =", Location = new Point(30, 38) });
            gbCoeff.Controls.Add(new Label { Text = "b =", Location = new Point(30, 73) });
            gbCoeff.Controls.Add(new Label { Text = "c =", Location = new Point(30, 108) });
            gbCoeff.Controls.Add(cbA);
            gbCoeff.Controls.Add(cbB);
            gbCoeff.Controls.Add(cbC);
            this.Controls.Add(gbCoeff);

            // Переменные
            var gbVar = new GroupBox { Text = "Переменные x, y, z", Location = new Point(430, 245), Size = new Size(350, 170) };

            tbX = new TextBox { Location = new Point(90, 35), Width = 140, Text = "4" };
            tbY = new TextBox { Location = new Point(90, 70), Width = 140, Text = "5" };
            tbZ = new TextBox { Location = new Point(90, 105), Width = 140, Text = "2" };

            cbIncludeZ = new CheckBox { Text = "Включить z в расчёт", Location = new Point(30, 140), Checked = true };
            cbIncludeZ.CheckedChanged += (s, e) => tbZ.Enabled = cbIncludeZ.Checked;

            gbVar.Controls.Add(new Label { Text = "x =", Location = new Point(30, 38) });
            gbVar.Controls.Add(new Label { Text = "y =", Location = new Point(30, 73) });
            gbVar.Controls.Add(new Label { Text = "z =", Location = new Point(30, 108) });
            gbVar.Controls.Add(tbX);
            gbVar.Controls.Add(tbY);
            gbVar.Controls.Add(tbZ);
            gbVar.Controls.Add(cbIncludeZ);
            this.Controls.Add(gbVar);

            // Кнопки
            btnCalculate = new Button
            {
                Text = "Вычислить W",
                Location = new Point(30, 435),
                Size = new Size(210, 50),
                Font = new Font("Segoe UI", 11, FontStyle.Bold),
                BackColor = Color.FromArgb(0, 122, 204),
                ForeColor = Color.White
            };
            btnCalculate.Click += btnCalculate_Click;

            btnClear = new Button { Text = "Очистить историю", Location = new Point(260, 435), Size = new Size(180, 50) };
            btnClear.Click += (s, e) => lbHistory.Items.Clear();

            this.Controls.Add(btnCalculate);
            this.Controls.Add(btnClear);

            // Результат
            var gbResult = new GroupBox { Text = "Результат расчёта", Location = new Point(30, 500), Size = new Size(750, 85) };

            lblResult = new Label
            {
                Text = "Результат: W = ?",
                Location = new Point(20, 30),
                Size = new Size(710, 40),
                Font = new Font("Segoe UI", 14, FontStyle.Bold),
                ForeColor = Color.DarkGreen
            };
            gbResult.Controls.Add(lblResult);
            this.Controls.Add(gbResult);

            // История
            lbHistory = new ListBox { Location = new Point(30, 600), Size = new Size(750, 80) };
            this.Controls.Add(lbHistory);
        }

        private void LoadData()
        {
            string[] coeffs = { "1.0", "1.5", "2.0", "2.5", "3.0" };

            cbA.Items.AddRange(coeffs);
            cbB.Items.AddRange(coeffs);
            cbC.Items.AddRange(coeffs);

            cbA.SelectedIndex = 2;   // 2.0
            cbB.SelectedIndex = 1;   // 1.5
            cbC.SelectedIndex = 3;   // 2.5
        }

        private void btnCalculate_Click(object sender, EventArgs e)
        {
            try
            {
                // Явная проверка
                if (cbA.SelectedIndex == -1 || cbB.SelectedIndex == -1 || cbC.SelectedIndex == -1)
                {
                    MessageBox.Show("Выберите коэффициенты a, b и c из списков!", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }

                if (string.IsNullOrWhiteSpace(tbX.Text) || string.IsNullOrWhiteSpace(tbY.Text) || string.IsNullOrWhiteSpace(tbZ.Text))
                {
                    MessageBox.Show("Заполните поля x, y и z числами!", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }

                double a = double.Parse(cbA.Text);
                double b = double.Parse(cbB.Text);
                double c = double.Parse(cbC.Text);
                double x = double.Parse(tbX.Text);
                double y = double.Parse(tbY.Text);
                double z = cbIncludeZ.Checked ? double.Parse(tbZ.Text) : 0;

                double W = 0;
                string method = rbMethod1.Checked ? "Способ 1 (прямой)" : "Способ 2 (цикл)";

                if (rbMethod1.Checked)
                    W = a * x + b * y + c * z;
                else
                {
                    double[] cf = { a, b, c };
                    double[] vr = { x, y, z };
                    for (int i = 0; i < 3; i++)
                        W += cf[i] * vr[i];
                }

                lbHistory.Items.Add($"{method} → W = {W:F4}");
                lblResult.Text = $"Результат: W = {W:F4}";
                lblResult.ForeColor = Color.DarkGreen;
            }
            catch (Exception ex)
            {
                MessageBox.Show($"Ошибка ввода!\nПроверьте поля x, y, z и выбранные коэффициенты.\n\n{ex.Message}", 
                    "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
    }
}