본문 바로가기

   
Programming/ADO.NET

winform 속성으로 DB 연결

반응형

메인폼 


using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Linq;

using System.Text;

using System.Windows.Forms;

using System.Data.SqlClient;

 

namespace today

{

       public partial class Form1 : Form

       {

             public Form1()

             {

                    InitializeComponent();

             }

 

             private void Form1_Load(object sender, EventArgs e)

             {

                    con.Open();//db접속

                    SelectAll();

             }

 

             //모든 레코드를 가져와서 리스트뷰에 출력하기

             public void SelectAll()

             {

                    //기존에 있던 리스트는 초기화 -> 새로운 항목으로..

                    listView1.Items.Clear();

                   

 

                    SqlDataReader reader = cmdSelectAll.ExecuteReader();

 

                    //레코드 -> ListViewItem 생성

                    while (reader.Read())

                    {

                           ListViewItem item = new ListViewItem(reader["seq"].ToString());

 

                           item.SubItems.Add(reader["name"].ToString());

                           item.SubItems.Add(reader["regDate"].ToString());

 

                           DateTime regDate = (DateTime)reader["regDate"];

 

                           item.SubItems.Add(regDate.ToLongDateString());

 

                           listView1.Items.Add(item);

                    }

                   

                    reader.Close();

             }

 

             private void listView1_MouseDoubleClick(object sender, MouseEventArgs e)

             {

                    //한명을 선택 -> View 띄우기

                    string seq = listView1.SelectedItems[0].Text;

                    //this.Text = seq;

 

                    Ex07_view view = new Ex07_view();

                    view.StartPosition = FormStartPosition.CenterParent;

                    view.Seq = seq;//**부모와 대화 프로퍼티에게 현재 seq를 반환

                    view.Owner = this;

                    view.ShowDialog();

             }

 

             private void button1_Click(object sender, EventArgs e)

             {

                    Ex07_add add = new Ex07_add();

                    add.StartPosition = FormStartPosition.CenterParent;

                    add.Owner = this;//내가 니부모다. 추가시키는 창한테 부모창을 건네준다.

                    add.ShowDialog();

             }

 

             private void button2_Click(object sender, EventArgs e)

             {

                    //검색하기

                    //1. 어느 컬럼?

                    //2. 검색어?

                    string serchText = textBox1.Text.Trim();

 

                    string searchColumn = "";

 

                    switch (comboBox1.SelectedItem.ToString())

                    {

                           case "번호":

                                 searchColumn = "seq";

                                 break;

                           case "이름":

                                 searchColumn = "name";

                                 break;

                           case "주소":

                                 searchColumn = "address";

                                 break;

                           case "나이":

                                 searchColumn = "age";

                                 break;

                    }

 

                    cmdSearch.CommandText = string.Format("SELECT seq, name, regDate FROM tblAddress WHERE {0} LIKE '%{1}%';", searchColumn, serchText.Replace("'", "''"));

 

                    //리스트 출력

                    SqlDataReader reader = cmdSearch.ExecuteReader();

 

                    //이전에 리스트 -> 초기화

                    listView1.Items.Clear();

 

                    while (reader.Read())

                    {

                           ListViewItem item = new ListViewItem(reader["seq"].ToString());

                           item.SubItems.Add(reader["name"].ToString());

 

                           DateTime regData = (DateTime)reader["regDate"];

                           item.SubItems.Add(regData.ToLongDateString());

 

                           listView1.Items.Add(item);

                    }

 

                    reader.Close();

             }

 

             private void button3_Click(object sender, EventArgs e)

             {

                    SelectAll();

             }

 

             private void Form1_FormClosed(object sender, FormClosedEventArgs e)

             {

                    con.Close();

             }

       }

}



추가 




using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Linq;

using System.Text;

using System.Windows.Forms;

 

using System.Data.SqlClient;

 

namespace today

{

       public partial class Ex07_add : Form

       {

             public Ex07_add()

             {

                    InitializeComponent();

             }

 

             private void Ex07_add_Load(object sender, EventArgs e)

             {

                    for (int i = 10; i < 50; i++)

                    {

                           comboBoxAge.Items.Add(i.ToString());

                    }

             }

 

             private void button1_Click(object sender, EventArgs e)

             {

                    //추가하기

                    con.Open();

 

                    //매개변수값 대입

                    cmdInsert.Parameters["@name"].Value = textBoxName.Text;

                    cmdInsert.Parameters["@age"].Value = comboBoxAge.SelectedItem.ToString();

                    cmdInsert.Parameters["@email"].Value = textBoxEmail.Text;

                    cmdInsert.Parameters["@address"].Value = textBoxAddress.Text;

                    cmdInsert.Parameters["@tel"].Value = textBoxTel.Text;

 

                    cmdInsert.ExecuteNonQuery();//반환값이 없는 INSERT 이니

 

                    con.Close();

 

                    //창닫기

                    this.Close();

 

                    //부모가 가지는 SelectAll() 호출(리스트 갱신)

                    ((Form1)this.Owner).SelectAll();

             }

 

             private void Ex07_add_FormClosed(object sender, FormClosedEventArgs e)

             {

                    con.Close();

             }

       }

}

 

 

수정 삭제 조회







using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Linq;

using System.Text;

using System.Windows.Forms;

 

using System.Data.SqlClient;

 

namespace today

{

       public partial class Ex07_view : Form

       {

 

             private string seq;//자신이 보여야할 회원번호

 

             public string Seq//프로퍼티

             {

                    set { this.seq = value; }

             }

 

             public Ex07_view()

             {

                    InitializeComponent();

             }

 

             private void Ex07_view_MouseDoubleClick(object sender, MouseEventArgs e)

             {

                    //한명을 선택 -> View 띄우기

             }

 

             private void Ex07_view_Load(object sender, EventArgs e)

             {

                    //콤보박스 초기화

                    for (int i = 10; i <= 50; i++)

                    {

                           comboBoxAge.Items.Add(i.ToString());

                    }

 

                    //부모가 건네준 회원번호를 조건으로 모든 컬럼값을 Select -> 컨트롤 출력

                    con.Open();

 

                    cmdSelectOne.Parameters["@seq"].Value = seq;

 

                    SqlDataReader reader = cmdSelectOne.ExecuteReader();

 

                    if (reader.Read())

                    {

                           labelSeq.Text = reader["seq"].ToString();

                           textBoxName.Text = reader["name"].ToString();

                           comboBoxAge.SelectedItem = reader["age"].ToString();

                           textBoxEmail.Text = reader["email"].ToString();

                           textBoxTel.Text = reader["tel"].ToString();

                           textBoxAddress.Text = reader["address"].ToString();

                           labelRegDate.Text = reader["regDate"].ToString();

 

                    }

 

                    reader.Close();

             }

 

             private void button1_Click(object sender, EventArgs e)

             {

                    //수정하기 DB는 열려 있는 상태

                    cmdUpdate.Parameters["@name"].Value = textBoxName.Text;

                    cmdUpdate.Parameters["@age"].Value = comboBoxAge.SelectedItem.ToString();

                    cmdUpdate.Parameters["@email"].Value = textBoxEmail.Text;

                    cmdUpdate.Parameters["@address"].Value = textBoxAddress.Text;

                    cmdUpdate.Parameters["@tel"].Value = textBoxTel.Text;

                    cmdUpdate.Parameters["@seq"].Value = seq;//이미 부모단에서 넘겨주었다. seq스번호를

 

                    cmdUpdate.ExecuteNonQuery();

                   

                    //창닫기 -> 리스트 갱신

                    this.Close();

 

                    ((Form1)this.Owner).SelectAll();

             }

 

             private void button2_Click(object sender, EventArgs e)

             {

                    //삭제하기

                    if (MessageBox.Show("정말 삭제하시겠습니까", "삭제확인", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes)

                    {

                           //cmdDelete

                           cmdDelete.Parameters["@seq"].Value = seq;

 

                           cmdDelete.ExecuteNonQuery();

 

                           this.Close();

 

                           ((Form1)this.Owner).SelectAll();

                    }

             }

       }

}

 

DataGridView

수정 삭제 조회를 컨트롤러가 자동으로 db연결을 해준다.




 using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Linq;

using System.Text;

using System.Windows.Forms;

 

namespace today

{

       public partial class Ex09_DataGridview : Form

       {

             public Ex09_DataGridview()

             {

                    InitializeComponent();

             }

 

             private void Ex09_DataGridview_Load(object sender, EventArgs e)

             {

                    sqlDataAdapter1.Fill(dataSet11.tblAddress);//데이터를 채워놓는다.

 

                    //데이터 바인딩

                    // - WPF(속성 <-> 속성)

                    // - Winform

                    // - ASP.NET

                    //공식적으로 데이터 바인딩 지원

 

                    //데이타 베이스에 제약사항을 모두 지켜준다.

                    dataGridView1.DataSource = dataSet11.tblAddress;

             }

 

             private void button1_Click(object sender, EventArgs e)

             {

                    //1. DataGridView는 오로지 데이터바인딩을 통해서만 데이터를 추가시킬 수 있음.(Items.Add() - 없음)

                    //2. DataGridView에서 데이터를 편집하게 되면 DataGridView DataSource에 설정된 DataSet의 데이터가 변경이 된다.

                    MessageBox.Show(dataSet11.tblAddress.Rows[0]["age"].ToString());

             }

 

             private void button2_Click(object sender, EventArgs e)

             {

                    //데이터베이스 서버에 반영시키기

                    //DataGridView에서 편집한 데이터를 실제 DB에 적용

                    //DataGridView로 편집해서 수정이된 DataSet을 소유하고 있는 DataAdapter가 반영 담당 객체

                    sqlDataAdapter1.Update(dataSet11.tblAddress);

             }

       }

}

 












 

반응형