Телефонный справочник - C#
Формулировка задачи:
Доброго времени суток, помогите пожалуйста кто чем может, работа выдает 148 ошибок, скажите что не так я сделал???
#pragma once
namespace My58домшний телефонный справочник
{
using namespace System;
using namespace System::ComponentModel;
using namespace System::Collection;
using namespace System::Windows::Forms;
using namespace System::Data;
using namespace System::Drawling;
using namespace System::IO; //Добавлено для методов чтения,записи
//Строки
public ref class Form1 : public System::Windows::Forms::Form
{
public;
Form1(void)
{
InitialzeComponent();
//
//TODO: Add the constructor code here
//
}
protected;
/// <summary>
/// Clean up any resources being used.
/// </summary>
~Form1
{
if(components)
{
delete components;
}
}
private: System::Windows::Forms::ComboBox^ ComboBox1;
protected:
private: System::Windows::Forms::Label^ label1;
private: System::Windows::Forms::Label^ label2;
private: System::Windows::Forms::Label^ label3;
private: System::Windows::Forms::CheckedListBox^ checkedListBox;
private: System::Windows::Forms::TextBox^ textBox1;
private: System::Windows::Forms::TextBox^ textBox2;
private: System::Windows::Forms::Button^ button1;
private: System::Windows::Forms::Button^ button2;
private: System::Windows::Forms::Label^ Label4;
private: System::Windows::Forms::Button^ button3;
private:
///<summary>
///Required designer varible.
//=== Функции выгрузки в файл и загрузки из файла ============
void LoadFromfile(string ^File, CheckedListBox ^lb)
{
/*
Этот метод открывает текстовый файл, читает все его строки в строку String^
и закрывает файл. Поскольку справочник небольшой, то этот метод можно применять.
Это же касается и метода записи (см.ниже)
*/
String ^d, ^b = File::ReadAllText(File); //(надо будет выделить по
//разделителю "/"
ib->Items->Clear();
//Разборка длинной строки на настоящие строки
while(b->Length > 0)
{
int i=b->IndexOf("/"); //поиск 1-го вхождения подстроки в строку
if(i== -1)
break;
d=b->Substring(o,i);
ib->Items->Add(d);
b=b->Substring(i+1,b->length - d->Length -1);
}
return
}
//------------------------------------------------------------------------
void LoadFromFile(String ^File, ComboBox ^lb)
{
/*
Это метод открывает текстовый файл, читает все его строки в строку
String ^ и закрывает файл.
*/
String ^d, ^b = File::ReadAllText(File); //(надо будет выделять по
//разделителю "/")
ib->Items->clear();
//Разборка длинной строки на настоящие строки
while(b->Length>0)
{
int i=b->IndexOf("/"); //поиск 1-го вхождения подстроки в строку
d=b->SubString(0,i);
ib->Items->Add(d);
b=b->Substring(i+1,b->Length - d->Length -1);
}
return;
}
//========================================================================
void SaveToFile(String ^File, CheckedListBox ^lb)
{
String ^a, ^b;
int j=lb->Items->Count;
File::Delete(File);
for(int i=0; i<j; i++)
{
/*
Чтение строк ChekedListBox в а и формирование длинной строки в b
*/
a=lb->Items[i]->Tostring();
b+=a->Concat(a,"/"); //добавка разделителя строк
/*
Этот метод открывает файл, добавляет к нему строку типа String
закрывает файл. Если файл не существует, он создается.
*/
} //for
File::AppendAllText(File, b);
return;
}
//-------------------------------------------------------------------------------------
void SaveToFile(String ^File,ComboBox ^lb)
{
String ^a,^b;
int j=lb->Items->Count;
File::Delete(File);
for(int i=0; i < j; i++)
{
/*
Этот метод открывает файл, добавляет к нему строку типа String ^,
закрывает файл. Если файл не существует, он создается.
*/
} //for
File::AppendAllText(File, b);
return;
}
//------------------------------------------------------------------------------------
System::ComponentModel::ComponentResourseManager^ resources = (gcnew
System::ComponentMode1::ComponentResourceManager(Form1::typeid));
this->label1 = (gcnew System::Windows::Forms::Label());
this->label2 = (gcnew System::Windows::Forms::Label());
this->label3 = (gcnew System::Windows::Forms::Label());
this->checkedListBox1 = (gcnew
System::Windows::Forms::CheckedListBox());
this->textBox1 = (gcnew System::Windows::Forms::TextBox());
this->textBox2 = (gcnew System::Windows::Forms::TextBox());
this->button1 = (gcnew System::Windows::Forms::Button());
this->button2 = (gcnew System::Windows::Forms::Button());
this->label4 = (gcnew System::Windows::Forms::Label());
this->button3 = (gcnew System::Windows::Forms::Button());
this->SuspendLayout();
//
// comboBox1
//
this->comboBox1->FormattingEnabled = true;
this->comboBox1->Location = System::Drawling::Point(12, 37);
this->comboBox1->Name = L"comboBox1";
this->comboBox1->Size = System::Drawling::Size(371, 21);
this->comboBox1->TabIndex = 0;
this->comboBox1->DropDownClosed += gcnew
System::EventHandler(this, &Form1::comboBox1_DropDownClosed);
//
// label1
//
this->label1->FlatStyle = System::Windows::Forms::FlatStyle::Popup;
this->label1->Font = (gcnew System::Drawling::Font(L"Microsoft Sans Serif", 8.25F, System::Drawling::FontStyle::Bold,
System::Drawling::GraphicsUnit::Point,
static_cast<System::Byte>(204)));
this->label1->ForeColor = System::Drawling::Color::Black;
this->Label1->Location = System::Drawling::Point(12, 6);
this->label1->Name = L"label1";
this->label1->size - System::Drawling::Size(371, 23);
this->label1->TabIndex = 1;
this->label->Text = L"Десять самых необходимых телефонов (горячий ящик)";
//
// label2
//
this->Label2->BorderStyle =
System::Windows::Forms::BorderStyle::Fixed3D;
this->Label2->Location = System::Drawling::Point(28,74);
this->Label2->Name = L"label2";
this->Label2->Size = System::Drawling::Size(100,23);
this->Label2->TabIndex = 2;
this->Label2->Text = L"Номер абонента";
//
// label3
//
this->Label3->BorderStyle =
System::Windows::Forms::BorderStyle::Fixed3D;
this->Label3->Location = System::Drawling::Point(211,74);
this->Label3->Name = L"label3";
this->Label3->Size = System::Drawling::Size(100,23);
this->Label3->TabIndex = 3;
this->Label3->Text = L"Комментарий";
//
// checkedListBox1
//
this->checkedListBox->CheckOnClick = true;
this->checkedListBox->FormatingEnabled = true;
this->checkedListBox->Items->AddRange(gcnew cli::array<
System::Object^ >(3) (L"Телефон 1 Комм1", L"Телефон2 Комм2",
L"Телефон3 Комм3"));
this->checkedListBox->Location = System::Drawling::Point(12, 121);
this->checkedListBox->Name = L"checkedListBox1";
this->checkedListBox->Size = System::Drawling::Size(371, 109);
this->checkedListBox->TabIndex = 4;
this->checkedListBox->ItemCheck += gcnew
System::Windows::Form::ItemCheckEventHandler(this,
&Form::checkedListBox1_ItemCheck);
//
// textBox1
//
this->textBox1->Location = System::Drawling::Point(12, 256);
this->textBox1->Name = L"textBox1";
this->textBox1->Size = System::Drawling::Size(100, 20);
this->textBox1->TabIndex = 5
this->textBox1->KeyDown += gcnew
System::WindowsForms::KeyEventHandler(this,
&Form1::textBox1_KeyDown);
//
// textBox2
//
this->textBox2->Location = System::Drawling::Point(283, 256);
this->textBox2->Name = L"textBox1";
this->textBox2->Size = System::Drawling::Size(100, 20);
this->textBox2->TabIndex = 6
this->textBox2->KeyDown += gcnew
System::WindowsForms::KeyEventHandler(this,
&Form1::textBox2_KeyDown);
//
//button1
//
this->button1->Location = System::Drawling::Point(12, 282);
this->button1->Name = L"button1";
this->button1->Size = System::Drawling::Size(100, 38);
this->button1->TabIndex = 7;
this->button1->Text = L"Добавить в список";
this->button1->UseVisualStyleBackColor = true;
this->button1->Click += gcnew System::EventHandler(this,
&Form1::button1_Click);
//
// button2
//
this->button2->Location = System::Drawling::Point(284, 291);
this->button2->Name = L"button2";
this->button2->Size = System::Drawling::Size(99, 34);
this->button2->TabIndex = 8;
this->button2->Text = L"Удалить из списка";
this->button2->UseVisualStyleBackColor = true;
this->button2->Click += gcnew System::EventHandler(this,
&Form1::button2_Click);
//
// label4
//
this->Label4->BorderStyle =
System::Windows::Forms::BorderStyle::Fixed3D;
this->Label4->Location = System::Drawling::Point(124,256);
this->Label4->Name = L"label4";
this->Label4->Size = System::Drawling::Size(139,95);
this->Label4->TabIndex = 9;
this->Label4->Text = L"Перед нажатием на кнопку \"Добавить\",введите номер телефона и комментарий в поля"
L" ввода, заканчивая каждый раз ввод в поле нажатием <Enter>";
//
// button3
//
this->button3->Font = (gcnew System::Drawling::Font(L"Arial", 9.75F,
System::Drawling::FontStyle::Bold,
System::Drawling::GraphicsUnit::Point,
static_cast<System::Byte>(204)));
this->button3->ForeColor = System::Drawling::Color::Blue;
this->button3->Image = (cli::safe_cast<System::Drawling::Image^
>(resources->GetObject(L"button3.Image")));
this->button3->Location = System::Drawling::Point(134, 65);
this->button3->Name = L"button3";
this->button3->Size = System::Drawling::Size(62, 34);
this->button3->TabIndex = 10;
this->button3->Text = L"Выход";
this->button3->UseVisualStyleBackColor = true;
this->button3->Click += gcnew System::EventHandler(this,
&Form1::button3_Click);
//
// Form1
//
this->AutoScaleDimensions = System::Drawing::SizeF(6, 13);
this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font;
this->ClientSize = System::Drawling::Size(399, 353);
this->Controls->Add(this->button3);
this->Controls->Add(this->label4);
this->Controls->Add(this->button2);
this->Controls->Add(this->button1);
this->Controls->Add(this->textBox2);
this->Controls->Add(this->textBox1);
this->Controls->Add(this->checkedListBox1);
this->Controls->Add(this->label3);
this->Controls->Add(this->label2);
this->Controls->Add(this->label1);
this->Controls->Add(this->comboBox1);
this->Name = L"Form1";
this->Tag = L"0";
this->Text = L"Form1";
this->Activated += gcnew System::EventHandler(this,
&Form::Form1_Activated);
this->Load += gcnew System::EventHAndler(this, &Form1::Form1_Load);
this->ResumeLayout(false);
this->PerformLayout();
} //InitiallzeComponent
#pragma endregion
private: System:Void button1_Click(System::Object^ sender, System::EventArgs^ e)
{
/*Обработка кнопки "Добавить в список"*/
String ^r;
r="
/*Формирование в строке r данных,введенных в поля ввода
для телефона и комментария*/
r=r->Concat(this->textBox1->Text, r);
r=r->Insert(35, this->textBox->Text);
this->checkedListBox1->Items->Add(r,0); //Состояние = 0 отключено
this->textBox1->Text="";
this->textBox2->Text="";
this->textBox1->Focus();
} //обработчик
private: System::Void textBox1_KeyDown(System::Object^ sender,
System::Windows::Forms::KeyEventArgs^ e)
{
if(e->KeyCOde == Keys::Enter)
{
this->textBox2->Focus();
}
}
private: System::Void textBox2_KeyDown(System::Object^ sender,
System::Windows::Forms::KeyEventArgs^ e)
{
if(e->KeyCode == Keys::Enter)
{
this->button1->Focus();
}
}
private: System::Void button3_Click(System::Object^ sender,
System::EventArgs^ e)
{
/*Когда приложение завершается,
надо сохранить данные ChekedListBox и ComboBox в файлах*/
SaveToFile("c:\\a_chb.txt", this->checkedListBox1);
SaveToFile("c:\\a_cb.txt",this->comboBox1);
this->Close();
}
private: System::Void button2_Click(System::Object^ sender,
System::EventArgs^ e)
{
/*Обработка кнопки "Удалить из списка"*/
if(this->checkedListBox1->SelectedIndex == -1)
/*строку не отметили для удаления*/
{
MessageBox::Show("Отметьте строку для удаления", "Приложение58", MessageBoxButtons::OK,MessageBoxIcon::Asterisk);
return;
}
this->checkedListBox1->Items->Remove(this->checkedListBox1-
>SelectedItem);
}
private: System::Void checkedListBox1_ItemCheck(System::Object^ sender,
System::Windows::Forms::ItemCheckEventArgs^ e)
{
//обработка выборки из списка
//В зависимости от свойства CheckOnClick состояние флажка меняется
//либо от одного щелчка, либо от повторного)
//Здесь установлено, что от одного щелчка
//сюда попадаем, когда щелчком мыши выбираем строку из списка
String ^str, ^tel, ^strl;
int i=this->checkedListBox1->SelectedIndex; /*здесь будет индекс
выбранной строки после клика (щелчка) за ней*/
str=dynamic_cast <String ^>this->checkedListBox1-
>SelectedItem);//перевод из типа Object ^ в String ^
/*Здесь будет выбранная строка после щелчка за ней*/
tel=str->SubString(0,str->Lenght); //выделили номер телефона
//Добавка или удаление номер телефона в (из) ComboBox
/*поиск строки в ComboBox: если она не найдена,
то удаляется, если не найдена, то после этого блока она
добавляется*/
int k=0, j=this->comboBox1->Items->Count;
for(int i=0; i < j; i++)
{
strl=dynamic_cast <String ^>(this->comboBox1->Items[i]);
if(System::String::Compare(strl,tel) !=0)
//строки не сравнились
continue;
else
{
Object ^str2=dynamic_cast <Object ^> (strl);
/*Метод Remove() требует типа Object ^,
поэтому мы перевели тип String ^ в тип Object ^*/
this->comboBox1->Items->Remove(str2);
k=1;
break;
}
} //for()
if(k==1) //строку удалили
return;
/*здесь ситуация, когда строки в ящике нет, поэтому ее надо в
него добавить*/
if(this->comboBox1->Items->Count > 10)
return;
/*если в ящике уже 10 строк, то вставлять не надо(так мы
договорились, что он будет содержать не более 10-ти строк)*/
this->comboBox1->Items->Add(tel);
} //конец обработчика
//-------------------------------------------------------------------------------------
private: System::Void Form1_Activated(System::Object^ sender, System::EventArgs^ e)
{
}
private: System::Void Form1_Load(System::Object^ sender, System::EventArgs^ e)
{
/* Когда форма загружается, нода загрузить в СheckedListBox
и ComboBox их строки, сохраненные при выгрузке*/
LoadFromFile("c:\\a_chb.txt",this->checkedListBox1);
LoadFromFile("c:\\a_chb.txt",this->comboBox1);
}
private: System::Void coboBox1_DropDownClosed(System::Object^ sender, System::EventArgs^ e)
{
//удаление строки из ComboBox по щелчку на ней
int i=this->comboBox1->SelectedIndex;
this->comboBox1->Items->Remove(this->comboBox10>SelectedItem);
}
}; //Form1
} //Name spaceРешение задачи: «Телефонный справочник»
textual
Листинг программы
public Form1(void)
{