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


Понял задание. Нужно создать программу "электронная сваха" (задание **) по методичке — с интерфейсом в дизайнере (Windows Forms на C#). Сделаю как студент первого курса: покажу дизайн формы и весь код.Теперь создам полное решение задания **: программа "Электронная сваха" на C# Windows Forms — с кодом формы и объяснением дизайнера.Выше — макет формы. Теперь весь код проекта.

---

## Как создать в дизайнере (пошагово)

1. Создай новый проект: **File → New Project → Windows Forms App (.NET Framework)** → назови `Svaha`
2. Открой `Form1.cs [Design]`
3. Расставь элементы управления из **Toolbox** согласно макету выше:

| Элемент | Name | Text/свойства |
|---|---|---|
| `GroupBox` | `grpGroom` | "Данные жениха" |
| `GroupBox` | `grpBride` | "Данные невесты" |
| `Label` x6 | — | "Возраст:", "Рост:", "Вес:" (для каждой группы) |
| `NumericUpDown` x6 | `nudGAge`, `nudGHeight`, `nudGWeight`, `nudBAge`, `nudBHeight`, `nudBWeight` | параметры кандидата |
| `NumericUpDown` x12 | `nudGAgeMin/Max`, `nudGHMin/Max`... | требования к партнёру |
| `Button` | `btnAddGroom` | "Добавить жениха" |
| `Button` | `btnAddBride` | "Добавить невесту" |
| `ListBox` | `lstGrooms` | список женихов |
| `ListBox` | `lstBrides` | список невест |
| `Button` | `btnFind` | "Найти пары" |
| `Button` | `btnSave` | "Сохранить файлы" |
| `Button` | `btnLoad` | "Загрузить файлы" |
| `ListBox` | `lstResult` | результат подбора |
| `StatusStrip` + 3x `ToolStripStatusLabel` | `lblStatus1/2/3` | строка статуса |

---

## Код Form1.cs

```csharp
using System;
using System.Collections.Generic;
using System.IO;
using System.Windows.Forms;

namespace Svaha
{
    // Структура кандидата
    struct Candidate
    {
        public int Number;
        public int Age;
        public int Height;
        public int Weight;
        // Требования к партнёру (мин/макс)
        public int AgeMin, AgeMax;
        public int HeightMin, HeightMax;
        public int WeightMin, WeightMax;

        // Конструктор
        public Candidate(int num, int age, int height, int weight,
                         int ageMin, int ageMax, int heightMin, int heightMax,
                         int weightMin, int weightMax)
        {
            Number = num;
            Age = age; Height = height; Weight = weight;
            AgeMin = ageMin; AgeMax = ageMax;
            HeightMin = heightMin; HeightMax = heightMax;
            WeightMin = weightMin; WeightMax = weightMax;
        }

        // Строка для ListBox
        public override string ToString()
        {
            return $"№{Number} | {Age}л | {Height}см | {Weight}кг";
        }

        // Строка для записи в файл
        public string ToFileLine()
        {
            return $"{Number} {Age} {Height} {Weight} " +
                   $"{AgeMin} {AgeMax} {HeightMin} {HeightMax} {WeightMin} {WeightMax}";
        }

        // Чтение из строки файла
        public static Candidate FromFileLine(string line)
        {
            string[] parts = line.Split(' ');
            return new Candidate(
                int.Parse(parts[0]), int.Parse(parts[1]),
                int.Parse(parts[2]), int.Parse(parts[3]),
                int.Parse(parts[4]), int.Parse(parts[5]),
                int.Parse(parts[6]), int.Parse(parts[7]),
                int.Parse(parts[8]), int.Parse(parts[9])
            );
        }
    }

    public partial class Form1 : Form
    {
        // Списки кандидатов
        List<Candidate> grooms = new List<Candidate>();
        List<Candidate> brides = new List<Candidate>();

        // Счётчики порядковых номеров
        int groomCount = 0;
        int brideCount = 0;

        // Пути к файлам
        string groomsFile = "grooms.txt";
        string bridesFile = "brides.txt";

        public Form1()
        {
            InitializeComponent();
        }

        // ====== ДОБАВЛЕНИЕ ЖЕНИХА ======
        private void btnAddGroom_Click(object sender, EventArgs e)
        {
            groomCount++;
            Candidate g = new Candidate(
                groomCount,
                (int)nudGAge.Value,
                (int)nudGHeight.Value,
                (int)nudGWeight.Value,
                (int)nudGAgeMin.Value,   (int)nudGAgeMax.Value,
                (int)nudGHMin.Value,     (int)nudGHMax.Value,
                (int)nudGWMin.Value,     (int)nudGWMax.Value
            );
            grooms.Add(g);
            lstGrooms.Items.Add(g.ToString());
            UpdateStatus();
        }

        // ====== ДОБАВЛЕНИЕ НЕВЕСТЫ ======
        private void btnAddBride_Click(object sender, EventArgs e)
        {
            brideCount++;
            Candidate b = new Candidate(
                brideCount,
                (int)nudBAge.Value,
                (int)nudBHeight.Value,
                (int)nudBWeight.Value,
                (int)nudBAgeMin.Value,   (int)nudBAgeMax.Value,
                (int)nudBHMin.Value,     (int)nudBHMax.Value,
                (int)nudBWMin.Value,     (int)nudBWMax.Value
            );
            brides.Add(b);
            lstBrides.Items.Add(b.ToString());
            UpdateStatus();
        }

        // ====== ПОИСК ПАР ======
        // Пара подходит если:
        //   - параметры невесты входят в требования жениха
        //   - параметры жениха входят в требования невесты
        private void btnFind_Click(object sender, EventArgs e)
        {
            lstResult.Items.Clear();
            int pairsFound = 0;

            foreach (Candidate g in grooms)
            {
                foreach (Candidate b in brides)
                {
                    bool groomLikesBride =
                        b.Age    >= g.AgeMin    && b.Age    <= g.AgeMax &&
                        b.Height >= g.HeightMin && b.Height <= g.HeightMax &&
                        b.Weight >= g.WeightMin && b.Weight <= g.WeightMax;

                    bool brideLikesGroom =
                        g.Age    >= b.AgeMin    && g.Age    <= b.AgeMax &&
                        g.Height >= b.HeightMin && g.Height <= b.HeightMax &&
                        g.Weight >= b.WeightMin && g.Weight <= b.WeightMax;

                    if (groomLikesBride && brideLikesGroom)
                    {
                        lstResult.Items.Add(
                            $"Пара: Жених №{g.Number} ({g.Age}л,{g.Height}см,{g.Weight}кг) " +
                            $"— Невеста №{b.Number} ({b.Age}л,{b.Height}см,{b.Weight}кг)"
                        );
                        pairsFound++;
                    }
                }
            }

            if (pairsFound == 0)
                lstResult.Items.Add("Подходящих пар не найдено.");

            lblStatus3.Text = $"Найдено пар: {pairsFound}";
        }

        // ====== СОХРАНЕНИЕ В ФАЙЛЫ ======
        private void btnSave_Click(object sender, EventArgs e)
        {
            // Сохраняем женихов
            using (StreamWriter sw = new StreamWriter(groomsFile, false))
            {
                sw.WriteLine(grooms.Count); // первая строка — количество
                foreach (Candidate g in grooms)
                    sw.WriteLine(g.ToFileLine());
            }

            // Сохраняем невест
            using (StreamWriter sw = new StreamWriter(bridesFile, false))
            {
                sw.WriteLine(brides.Count);
                foreach (Candidate b in brides)
                    sw.WriteLine(b.ToFileLine());
            }

            MessageBox.Show("Файлы сохранены:\n" + groomsFile + "\n" + bridesFile,
                            "Сохранение", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        // ====== ЗАГРУЗКА ИЗ ФАЙЛОВ ======
        private void btnLoad_Click(object sender, EventArgs e)
        {
            grooms.Clear();
            brides.Clear();
            lstGrooms.Items.Clear();
            lstBrides.Items.Clear();
            lstResult.Items.Clear();

            // Загружаем женихов
            if (File.Exists(groomsFile))
            {
                using (StreamReader sr = new StreamReader(groomsFile))
                {
                    int count = int.Parse(sr.ReadLine());
                    for (int i = 0; i < count; i++)
                    {
                        Candidate g = Candidate.FromFileLine(sr.ReadLine());
                        grooms.Add(g);
                        lstGrooms.Items.Add(g.ToString());
                    }
                }
                groomCount = grooms.Count;
            }

            // Загружаем невест
            if (File.Exists(bridesFile))
            {
                using (StreamReader sr = new StreamReader(bridesFile))
                {
                    int count = int.Parse(sr.ReadLine());
                    for (int i = 0; i < count; i++)
                    {
                        Candidate b = Candidate.FromFileLine(sr.ReadLine());
                        brides.Add(b);
                        lstBrides.Items.Add(b.ToString());
                    }
                }
                brideCount = brides.Count;
            }

            UpdateStatus();
            MessageBox.Show("Файлы загружены!", "Загрузка",
                            MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        // Обновить строку статуса
        private void UpdateStatus()
        {
            lblStatus1.Text = $"grooms.txt: {grooms.Count} записей";
            lblStatus2.Text = $"brides.txt: {brides.Count} записей";
        }
    }
}
```

---

## Как подключить события в дизайнере

В дизайнере дважды кликни по каждой кнопке — Visual Studio сам создаст обработчик `_Click`. Либо в **Properties → Events (⚡)** выбери нужное событие и нажми Enter.

## Формат файлов

`grooms.txt` / `brides.txt` — текстовый файл:
```
3
1 28 178 75 22 30 160 175 50 68
2 32 182 82 20 28 158 172 48 65
3 26 175 70 23 29 163 170 52 66
```
Первая строка — количество кандидатов, далее по одной записи на строку.

## Тестовые данные (не менее 10)

Добавь в программу минимум 5 женихов и 5 невест с разными требованиями, чтобы получились как минимум 2–3 совпадающих пары — это и будет демонстрация работы программы.