C#

31.C#_WinForm - C# 주소록 (1)

Godffs 2009. 9. 3. 13:33
반응형

C# 윈폼으로 주소록을 만드는 예제입니다
구현기능
1. 이름, 휴대폰, 이메일 입력 후 저장버튼 클릭 시 입력내용 텍스트파일 저장
2. 프로그램 로드(재시작)시 저장된 텍스트내용 DataGrid에 출력
3. 입력 버튼 클릭시 텍스트박스 초기화(빈공간)으로 바꾸기

▶ 코드 작시 주의사항 ◀
예제에서는 코드를 추가 했습니다. 삭제 안했어요...


C# 윈폼을 새로 추가합니다. ( 새프로젝트 이름 - FrmMain )

FrmMain.Designer.cs

[그림31-1]
        private System.Windows.Forms.Button btnSave;
        private System.Windows.Forms.DataGridView dataGridView;
        private System.Windows.Forms.Button btnOK;
        private System.Windows.Forms.TextBox txtEMail;
        private System.Windows.Forms.TextBox txtPhone;
        private System.Windows.Forms.TextBox txtName;
        private System.Windows.Forms.Label label3;
        private System.Windows.Forms.Label label2;
        private System.Windows.Forms.Label label1;

먼저 해당 프로젝트에서 클래스 파일을 추가합니다. ( 이름 : Address.cs )

Address.cs
class Address
{
    public int Num { get; set; }
    public string Name { get; set; }
    public string  Mobile { get; set; }
    public string Email { get; set; }
}

FrmMain.cs (btnOK_Click 이벤트 코드 작성)
public partial class FrmMain : Form
{
    private List<Address> addr; //메모리상에 보관

    private void btnOK_Click(object sender, EventArgs e)
    {
        Address a = new Address();

        a.Num = addr.Count + 1;
        a.Name = txtName.Text.Trim(); //양쪽 공백 없애기
        a.Mobile = txtPhone.Text.Trim();
        a.Email = txtEMail.Text.Trim();

        addr.Add(a);
        clearTextBox(); //텍스트박스 초기화 메소드 호출
        DisplayData(); //출력
    }

    //텍스트박스 초기화
    private void clearTextBox()
    {
        //빈 문자열로 출력
        txtName.Text = txtPhone.Text = txtEMail.Text = String.Empty;
    }

    //출력을 위한 메소드
    private void DisplayData()
    {
        var q = (from a in addr select a).ToList();
        this.dataGridView.DataSource = q;
    }
}

FrmMain.cs (btnSave_Click 이벤트 코드 작성)
public partial class FrmMain : Form
{
    //파일,디렉토리 경로표시로 경로를 묶을때 편리함
    private string dir = Path.Combine(Application.StartupPath,
         "Myaddress.txt");

    private void btnSave_Click(object sender, EventArgs e)
    {
        if (addr.Count > 0)
        {
            SaveData();
        }
    }

    private void SaveData()
    {
        StringBuilder sb = new StringBuilder();
       
        foreach (Address a in addr)
        {
            sb.Append(String.Format("{0},{1},{2},{3}\r\n",
            a.Num, a.Name, a.Mobile, a.Email));
        }
           
        StreamWriter sw = new StreamWriter(dir, false, Encoding.Default);
        sw.WriteLine(sb.ToString());
        sw.Close();
        sw.Dispose();

        MessageBox.Show("저장되었습니다.");
    }
}

FrmMain.cs (FrmMain_Load 이벤트 코드 작성)
private void FrmMain_Load(object sender, EventArgs e)
{
        if (File.Exists(dir)) //파일이 있다면
        {
                LoadData();
        }
}

private void LoadData()
{
        StreamReader sr = new StreamReader(dir, Encoding.Default);

        while (sr.Peek() >= 0) //-1 : 더이상 읽을 문자가 없을때
        {
                //한줄만 읽기 전체는 ReadEnd, Split는 콤마로 구분
                string[] arr = sr.ReadLine().Trim().Split(',');

                if (arr[0] != "" && arr[0] != null)
                {
                    Address a = new Address();
                    a.Num = Convert.ToInt32(arr[0]);
                    a.Name = arr[1];
                    a.Mobile = arr[2];
                    a.Email = arr[3];

                    addr.Add(a);
                }
            }
            sr.Close();
            sr.Dispose();
            DisplayData();
        }
}

- 미완성입니다. 이어서 계속 -

31Address.zip
다운로드

반응형