티스토리 뷰
[1]전화번호부 구현
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.OleDb;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace _32_PhoneBook2
{
public partial class Form1 : Form
{
OleDbConnection conn = null;
OleDbCommand comm = null;
OleDbDataReader reader = null;
string connStr = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\choi\Documents\Studb.accdb";
public Form1()
{
InitializeComponent();
Showstudent();
}
void Showstudent()
{
if (conn == null)
{
conn = new OleDbConnection(connStr);
conn.Open();
}
string sql = "SELECT * FROM Studb";
comm = new OleDbCommand(sql, conn);
reader = comm.ExecuteReader();
while (reader.Read())
{
string x = "";
x += reader["ID"] + "\t";
x += reader["sid"] + "\t";
x += reader["sname"] + "\t";
x += reader["phone"];
lbStudent.Items.Add(x);
}
reader.Close();
conn.Close();
conn = null;
}
private void button2_Click(object sender, EventArgs e)
{
if (textBox2.Text == "" || textBox3.Text == "" || textBox4.Text == "")
return;
ConnOpen();
string sql = string.Format("INSERT INTO studb(sid, sname, phone) VALUES({0}, '{1}', '{2}')", textBox2.Text, textBox3.Text, textBox4.Text);
//학번이 8자리 이상이어야 \t가 작동함
comm = new OleDbCommand(sql, conn);
int x = comm.ExecuteNonQuery();
if (x == 1)
MessageBox.Show("정상삽입");
ConnClose();
}
private void lbStudent_SelectedIndexChanged_1(object sender, EventArgs e)
{
ListBox lb = (ListBox)sender;
if (lb.SelectedItem == null)
return;
string[] s = lb.SelectedItem.ToString().Split('\t');
//MessageBox.Show(lb.SelectedItem.ToString());
textBox1.Text = s[0];
textBox2.Text = s[1];
textBox3.Text = s[2];
textBox4.Text = s[3];
}
}
}
리스트박스의 changed_index와
추가버튼의 click 이벤트함수를 작성해보았다.
그 전에 연결하는 함수와 연결을 끊는 함수를 따로 만들어 주었다.
private void ConnOpen()
{
if (conn == null)
{
conn = new OleDbConnection(connStr);
conn.Open();
}
}
conn이 null일 때(비어있을 때)
connstr의 provider와 scource를 참조하여 conn을 설정해주고
conn을 토대로 open해주는 메서드이다.
private void ConnClose()
{
conn.Close();
conn = null;
lbStudent.Items.Clear();
Showstudent();
}
연결을 끊어주는 ConnClose()함수이다.
연결을 닫고 초기화해준다
그 후 현재 listbox에 남아있는 내용을 clear해준 뒤 showstudent로 다시 값을 불러온다.
private void button2_Click(object sender, EventArgs e)
{
if (textBox2.Text == "" || textBox3.Text == "" || textBox4.Text == "")
return;
ConnOpen();
string sql = string.Format("INSERT INTO studb(sid, sname, phone) VALUES({0}, '{1}', '{2}')", textBox2.Text, textBox3.Text, textBox4.Text);
//학번이 8자리 이상이어야 \t가 작동함
comm = new OleDbCommand(sql, conn);
int x = comm.ExecuteNonQuery();
if (x == 1)
MessageBox.Show("정상삽입");
ConnClose();
}
추가버튼의 함수 구현부이다.
학번,이름,전화번호에 대당하는 textbox2,3,4가 하나라도 빈칸인 경우 value없이 리턴한다.
아니라면 ConnOpen()함수를 사용하여 DB에 connection해준다.
string type sql을 지정해주고 SQL문법에 맞추어 format된 문장을 넣어준다.
커맨드comm을 방금 지정한 sql과 conn을 인자로 설정해준다.
참고로 ExecuteNonQuery()는 CommandText를 Connection에 보내고, SqlDataReader를 빌드하는 방식으로 구동된다.
현재 프로그램에서는 Connection = conn , SqlDataReader = sql로 지정해준 것이다.
그리고 정수형을 반환한다.
이 반환받은 값을 x에 넣어준 뒤
x==1이면 MessageBox를 띄운다.
그 후 ConnClose()를 사용하여 다시 연결을 끊고 conn=null로 바꿔준다.
private void lbStudent_SelectedIndexChanged_1(object sender, EventArgs e)
{
ListBox lb = (ListBox)sender;
if (lb.SelectedItem == null)
return;
string[] s = lb.SelectedItem.ToString().Split('\t');
//MessageBox.Show(lb.SelectedItem.ToString());
textBox1.Text = s[0];
textBox2.Text = s[1];
textBox3.Text = s[2];
textBox4.Text = s[3];
}
다음은 리스트박스의 선택값이 바뀌었을 때의 이벤트함수 내용이다.
ListBox클래스의 lb를 생성하고 sender값을 받아준다.
selecteditem==null이면 실행하지 않으므로 form이 로드되었을 땐 실행하지 않는 것이다.
그 후 string타입의 배열 s를 생성하여 선택된 item을 string으로 변경해준 뒤 \t로 구분하여 한 칸에 하나씩 저장해준다.
ID.Text = s[0]
sid.Text = s[1]
sname.Text = s[2]
phone.Text = s[3]
으로 저장해준다.
여기까지 구현하였고 나머지 버튼들은 다음시간에 구현 할 예정이다.
'VS-02분반수업' 카테고리의 다른 글
VP02(22-05-11) (0) | 2022.05.16 |
---|---|
VP(22-05-06) (0) | 2022.05.08 |
VS02(22-05-01) (0) | 2022.05.02 |
VS02(22-04-15) (0) | 2022.04.20 |
VS02(22-04-06) (0) | 2022.04.09 |