Есть такая задача:
Создайте форму, содержащую компоненты: 1 кнопку (обозначим В1), 1 списочный компонент для выбора элементов (LB1), 1 компонент для ввода числового значения с кнопками вверх-вниз (N1). Форма и компоненты имеют следующие исходные состояния:
- цвет формы – серый;
- список LB1 cодержит 6 элементов, именованных следующим образом: «Черный», «Белый», «Красный», «Синий», «Зеленый», «Желтый».
Реализовать обработчики событий:
- при нажатии на кнопку «Удалить» - из компоненты LB1 удаляется элемент с индексом, заданным в N1 (если в LB1 не существует элемента с указанным индексом, то никаких действий не производить);
- при выборе элемента LB1 (двойным кликом) – цвет формы меняется на цвет, соответствующий словесному описанию цвета в выбранном элементе LB1;
- при двойном клике на форме – возвращаются исходные состояния формы и компонентов.
Интересует момент с кнопкой "Удалить"
Написал такой код:
C++ |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
| private: System::Void button1_Click(System::Object^ sender, System::EventArgs^ e) {
if (numericUpDown1->Value > 6)
listBox1->Items->Remove("");
else if (numericUpDown1->Value > 5)
listBox1->Items->Remove("Желтый");
else if (numericUpDown1->Value > 4)
listBox1->Items->Remove("Зеленый");
else if (numericUpDown1->Value > 3)
listBox1->Items->Remove("Синий");
else if (numericUpDown1->Value > 2)
listBox1->Items->Remove("Красный");
else if (numericUpDown1->Value > 1)
listBox1->Items->Remove("Белый");
else if (numericUpDown1->Value > 0)
listBox1->Items->Remove("Черный");
} |
|
Как понятно, при таком коде при удалении, например, компонента "Белый", "Красный" останется третьим, а должен стать вторым. Как это реализовать?
Код полностью:
Кликните здесь для просмотра всего текста
C++ |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
| #pragma once
namespace Project1 {
using namespace System;
using namespace System::ComponentModel;
using namespace System::Collections;
using namespace System::Windows::Forms;
using namespace System::Data;
using namespace System::Drawing;
/// <summary>
/// Сводка для MyForm
/// </summary>
public ref class MyForm : public System::Windows::Forms::Form
{
public:
MyForm(void)
{
InitializeComponent();
//
//TODO: добавьте код конструктора
//
}
protected:
/// <summary>
/// Освободить все используемые ресурсы.
/// </summary>
~MyForm()
{
if (components)
{
delete components;
}
}
private: System::Windows::Forms::NumericUpDown^ numericUpDown1;
private: System::Windows::Forms::Button^ button1;
private: System::Windows::Forms::ListBox^ listBox1;
protected:
protected:
private:
/// <summary>
/// Обязательная переменная конструктора.
/// </summary>
System::ComponentModel::Container^ components;
#pragma region Windows Form Designer generated code
/// <summary>
/// Требуемый метод для поддержки конструктора — не изменяйте
/// содержимое этого метода с помощью редактора кода.
/// </summary>
void InitializeComponent(void)
{
this->numericUpDown1 = (gcnew System::Windows::Forms::NumericUpDown());
this->button1 = (gcnew System::Windows::Forms::Button());
this->listBox1 = (gcnew System::Windows::Forms::ListBox());
(cli::safe_cast<System::ComponentModel::ISupportInitialize^>(this->numericUpDown1))->BeginInit();
this->SuspendLayout();
//
// numericUpDown1
//
this->numericUpDown1->Location = System::Drawing::Point(46, 128);
this->numericUpDown1->Name = L"numericUpDown1";
this->numericUpDown1->Size = System::Drawing::Size(160, 20);
this->numericUpDown1->TabIndex = 0;
this->numericUpDown1->ValueChanged += gcnew System::EventHandler(this, &MyForm::numericUpDown1_ValueChanged);
//
// button1
//
this->button1->Location = System::Drawing::Point(46, 172);
this->button1->Name = L"button1";
this->button1->Size = System::Drawing::Size(160, 23);
this->button1->TabIndex = 3;
this->button1->Text = L"Удалить";
this->button1->UseVisualStyleBackColor = true;
this->button1->Click += gcnew System::EventHandler(this, &MyForm::button1_Click);
//
// listBox1
//
this->listBox1->FormattingEnabled = true;
this->listBox1->Items->AddRange(gcnew cli::array< System::Object^ >(6) {
L"Черный", L"Белый", L"Красный", L"Синий", L"Зеленый",
L"Желтый"
});
this->listBox1->Location = System::Drawing::Point(46, 27);
this->listBox1->Name = L"listBox1";
this->listBox1->Size = System::Drawing::Size(160, 95);
this->listBox1->TabIndex = 4;
this->listBox1->SelectedIndexChanged += gcnew System::EventHandler(this, &MyForm::listBox1_SelectedIndexChanged_1);
this->listBox1->DoubleClick += gcnew System::EventHandler(this, &MyForm::listBox1_DoubleClick);
//
// MyForm
//
this->AutoScaleDimensions = System::Drawing::SizeF(6, 13);
this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font;
this->BackColor = System::Drawing::Color::Gray;
this->ClientSize = System::Drawing::Size(250, 219);
this->Controls->Add(this->listBox1);
this->Controls->Add(this->button1);
this->Controls->Add(this->numericUpDown1);
this->Name = L"MyForm";
this->Text = L"Лабораторная 1";
this->Load += gcnew System::EventHandler(this, &MyForm::MyForm_Load);
this->DoubleClick += gcnew System::EventHandler(this, &MyForm::MyForm_DoubleClick);
(cli::safe_cast<System::ComponentModel::ISupportInitialize^>(this->numericUpDown1))->EndInit();
this->ResumeLayout(false);
}
#pragma endregion
private: System::Void numericUpDown1_ValueChanged(System::Object^ sender, System::EventArgs^ e) {
}
// 0 = 1
// 1 = 2
private: System::Void button1_Click(System::Object^ sender, System::EventArgs^ e) {
if (numericUpDown1->Value > 6)
listBox1->Items->Remove("");
else if (numericUpDown1->Value > 5)
listBox1->Items->Remove("Желтый");
else if (numericUpDown1->Value > 4)
listBox1->Items->Remove("Зеленый");
else if (numericUpDown1->Value > 3)
listBox1->Items->Remove("Синий");
else if (numericUpDown1->Value > 2)
listBox1->Items->Remove("Красный");
else if (numericUpDown1->Value > 1)
listBox1->Items->Remove("Белый");
else if (numericUpDown1->Value > 0)
listBox1->Items->Remove("Черный");
}
private: System::Void MyForm_Load(System::Object^ sender, System::EventArgs^ e) {
}
private: System::Void listBox1_SelectedIndexChanged_1(System::Object^ sender, System::EventArgs^ e) {
}
private: System::Void MyForm_DoubleClick(System::Object^ sender, System::EventArgs^ e) {
BackColor = Color::Silver;
numericUpDown1->Value = 0;
listBox1->Items->Clear();
listBox1->Items->Insert(0, "Черный");
listBox1->Items->Insert(1, "Белый");
listBox1->Items->Insert(2, "Красный");
listBox1->Items->Insert(3, "Синий");
listBox1->Items->Insert(4, "Зеленый");
listBox1->Items->Insert(5, "Желтый");
}
private: System::Void listBox1_DoubleClick(System::Object^ sender, System::EventArgs^ e) {
if (listBox1->Text == "Черный")
BackColor = Color::Black;
if (listBox1->Text == "Белый")
BackColor = Color::White;
if (listBox1->Text == "Красный")
BackColor = Color::Red;
if (listBox1->Text == "Синий")
BackColor = Color::Blue;
if (listBox1->Text == "Зеленый")
BackColor = Color::Green;
if (listBox1->Text == "Желтый")
BackColor = Color::Yellow;
}
};
} |
|