C# BookRentalShopApp
Main 화면
using BookRentalShop.Helpers;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace BookRentalShop
{
public partial class FrmMain : Form
{
#region <각화면 폼>
FrmGenre frmGenre = null;
FrmBooks frmBooks = null;
#endregion
#region<생성자>
public FrmMain()
{
InitializeComponent();
}
#endregion
#region<이벤트 핸들러>
private void FrmMain_Load(object sender, EventArgs e)
{
FrmLogin frm= new FrmLogin();
frm.ShowDialog();
LblUserID.Text = Commons.LoginID;
LblLoginDatetime.Text ="/ "+DateTime.Now.ToString();
}
private void ExitToolsStripMenuItem_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void MniGenre_Click(object sender, EventArgs e)
{
frmGenre = ShowActiveForm(frmGenre, typeof(FrmGenre)) as FrmGenre;
}
private void FrmMain_FormClosing(object sender, FormClosingEventArgs e)
{
if (MessageBox.Show("종료하시겠습니까?", "경고", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
e.Cancel = false;
Environment.Exit(0);
}
else
{
e.Cancel = true;
}
}
private void MniBookInfo_Click(object sender, EventArgs e)
{
frmBooks = ShowActiveForm(frmBooks, typeof(FrmBooks)) as FrmBooks;
}
private void MniMember_Click(object sender, EventArgs e)
{
}
private void MniRental_Click(object sender, EventArgs e)
{
}
private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
{
}
#endregion
private Form ShowActiveForm(Form form, Type type)
{
if(form == null)
{
form=(Form)Activator.CreateInstance(type);
form.MdiParent = this;
form.WindowState = FormWindowState.Normal;
form.Show();
}
else
{
if(form.IsDisposed)
{
form = (Form)Activator.CreateInstance(type);
form.MdiParent = this;
form.WindowState = FormWindowState.Normal;
form.Show();
}
else
{
form.Activate();
}
}
return form;
}
}
}
Login 화면
using System;
using System.Windows.Forms;
using BookRentalShop.Helpers;
using MySql.Data.MySqlClient;
namespace BookRentalShop
{
public partial class FrmLogin : Form
{
private bool isLogined = false;
public FrmLogin()
{
InitializeComponent();
}
private void BtnLogin_Click(object sender, EventArgs e)
{
isLogined = LoginProcess();
if (isLogined)
{
this.Close();
}
else
{
return;
}
}
private void BtnCancel_Click(object sender, EventArgs e)
{
Environment.Exit(0);
}
private void FrmLogin_FormClosed(object sender, FormClosedEventArgs e)
{
if (isLogined != true)
{
Environment.Exit(0);
}
}
private void TxtPassword_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == 13)
{
BtnLogin_Click(sender, e);
}
}
private void TxtUserid_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == 13)
{
TxtPassword.Focus();
}
}
private bool LoginProcess()
{
if (string.IsNullOrEmpty(TxtUserid.Text) || string.IsNullOrEmpty(TxtPassword.Text))
{
MessageBox.Show("아이디/패스워드를 입력하세요!", "오류", MessageBoxButtons.OK, MessageBoxIcon.Error);
return false;
}
string strUserId = "";
string strPassword = "";
try
{
using (MySqlConnection conn = new MySqlConnection(Helpers.Commons.ConnString))
{
conn.Open();
#region<DB 쿼리를 위한 구성>
string selQuery = @"SELECT userid
, password
FROM usertbl
WHERE userid = @userid AND password = @password";
MySqlCommand selCmd = new MySqlCommand(selQuery, conn);
MySqlParameter prmUserid = new MySqlParameter("@userid", TxtUserid.Text);
MySqlParameter prmPassword = new MySqlParameter("@password", TxtPassword.Text);
selCmd.Parameters.Add(prmUserid);
selCmd.Parameters.Add(prmPassword);
#endregion
MySqlDataReader reader = selCmd.ExecuteReader();
if (reader.Read())
{
strUserId = reader["userid"] != null ? reader["userid"].ToString() : "-";
strPassword = reader["Password"] != null ? reader["Password"].ToString() : "--";
Commons.LoginID = strUserId;
return true;
}
else
{
MessageBox.Show($"로그인정보가 없음", "오류", MessageBoxButtons.OK, MessageBoxIcon.Error);
Commons.LoginID = strUserId;
return false;
}
}
}
catch (Exception ex)
{
MessageBox.Show("로그인 정보 오류!", "오류", MessageBoxButtons.OK, MessageBoxIcon.Error);
return false;
}
}
}
}
FrmGenre (책 장르 관리) 화면
using MySql.Data.MySqlClient;
using System;
using System.Data;
using System.Windows.Forms;
using BookRentalShop.Helpers;
namespace BookRentalShop
{
public partial class FrmGenre : Form
{
bool isNew = false;
#region<생성자>
public FrmGenre()
{
InitializeComponent();
}
#endregion
#region<이벤트 핸들러>
private void FrmGenre_Load(object sender, EventArgs e)
{
isNew = true;
RefreshData();
}
private void BtnNew_Click(object sender, EventArgs e)
{
ClearInputs();
}
private void BtnSave_Click(object sender, EventArgs e)
{
if (CheckValidation() != true)
{
return;
}
SaveData();
RefreshData();
ClearInputs();
}
private void BtnDel_Click(object sender, EventArgs e)
{
if (isNew == true)
{
MessageBox.Show("삭제할 데이터를 선택하세요", "오류", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
using (MySqlConnection conn = new MySqlConnection(Helpers.Commons.ConnString))
{
if(conn.State==ConnectionState.Closed)
{
conn.Open();
}
string strChkQuery = "SELECT COUNT(*) FROM bookstbl WHERE Division = @Division";
MySqlCommand chkCmd = new MySqlCommand(strChkQuery, conn);
MySqlParameter prmDivision = new MySqlParameter("@Division", TxtDivision.Text);
chkCmd.Parameters.Add(prmDivision);
var result = chkCmd.ExecuteScalar();
if(result.ToString()!="0")
{
MessageBox.Show("FK로 지정되어있는 도서코드입니다.", "삭제", MessageBoxButtons.OK, MessageBoxIcon.Information);
return;
}
}
if (MessageBox.Show(this, "삭제하시겠습니까?", "삭제", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
{
return;
}
DeleteData();
RefreshData();
ClearInputs();
}
private void DgvResult_CellClick(object sender, DataGridViewCellEventArgs e)
{
if (e.RowIndex > -1)
{
var selData = DgvResult.Rows[e.RowIndex];
TxtDivision.Text = selData.Cells[0].Value.ToString();
TxtNames.Text = selData.Cells[1].Value.ToString();
TxtDivision.ReadOnly = true;
isNew = false;
}
}
#endregion
#region <커스텀 메서드>
private void RefreshData()
{
try
{
using (MySqlConnection conn = new MySqlConnection(Helpers.Commons.ConnString))
{
if (conn.State == ConnectionState.Closed)
{
conn.Open();
}
var SelQuery = @"SELECT Division
, Names
FROM divtbl";
MySqlDataAdapter adapter = new MySqlDataAdapter(SelQuery, conn);
DataSet ds = new DataSet();
adapter.Fill(ds, "divtbl");
DgvResult.DataSource = ds;
DgvResult.DataMember = "divtbl";
DgvResult.Columns[0].HeaderText = "장르코드";
DgvResult.Columns[1].HeaderText = "장르명";
}
}
catch (Exception ex)
{
MessageBox.Show($"비정상적 오류 : {ex.Message}", "오류", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ClearInputs()
{
TxtDivision.Text = TxtNames.Text = string.Empty;
TxtDivision.ReadOnly = false;
TxtDivision.Focus();
isNew = true;
}
private bool CheckValidation()
{
var result = true;
var errorMsg = string.Empty;
if (string.IsNullOrEmpty(TxtDivision.Text))
{
result = false;
errorMsg += "※ 장르코드을 입력하세요.\r\n";
}
if (string.IsNullOrEmpty(TxtNames.Text))
{
result = false;
errorMsg += "※ 장르명을 입력하세요\r\n";
}
if (result == false)
{
MessageBox.Show(errorMsg, "오류", MessageBoxButtons.OK, MessageBoxIcon.Error);
return result;
}
else
{
return result;
}
}
private void SaveData()
{
try
{
using (MySqlConnection conn = new MySqlConnection(Helpers.Commons.ConnString))
{
if (conn.State == ConnectionState.Closed)
{
conn.Open();
}
var query = "";
if (isNew)
{
query = @"INSERT INTO divtbl
VALUES(@Division, @Names)";
}
else
{
query = @"UPDATE divtbl
SET Names = @Names
WHERE Division = @Division";
}
MySqlCommand cmd = new MySqlCommand(query, conn);
MySqlParameter prmDivision = new MySqlParameter("@Division", TxtDivision.Text);
MySqlParameter prmNames = new MySqlParameter("@Names", TxtNames.Text);
cmd.Parameters.Add(prmDivision);
cmd.Parameters.Add(prmNames);
var result = cmd.ExecuteNonQuery();
if (result != 0)
{
MessageBox.Show("저장 성공!", "저장", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
MessageBox.Show("저장실패!", "저장", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
catch (Exception ex)
{
MessageBox.Show($"비정상적 오류 : {ex.Message}", "오류", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void DeleteData()
{
try
{
using (MySqlConnection conn = new MySqlConnection(Helpers.Commons.ConnString))
{
if (conn.State == ConnectionState.Closed)
{
conn.Open();
}
var query = @"DELETE FROM divtbl
WHERE Division = @Division";
MySqlCommand cmd = new MySqlCommand(query, conn);
MySqlParameter prmDivision = new MySqlParameter("@Division", TxtDivision.Text);
cmd.Parameters.Add(prmDivision);
var result = cmd.ExecuteNonQuery();
if (result != 0)
{
MessageBox.Show("삭제 성공!", "삭제", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
MessageBox.Show("삭제실패!", "삭제", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
catch (Exception ex)
{
MessageBox.Show($"비정상적 오류 : {ex.Message}", "오류", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
#endregion
}
}
FrmBooks (책 정보 관리) 화면
using MySql.Data.MySqlClient;
using System;
using System.Data;
using System.Windows.Forms;
using BookRentalShop.Helpers;
using System.Collections.Generic;
namespace BookRentalShop
{
public partial class FrmBooks : Form
{
bool isNew = false;
#region<생성자>
public FrmBooks()
{
InitializeComponent();
}
#endregion
#region<이벤트 핸들러>
private void FrmBooks_Load(object sender, EventArgs e)
{
isNew = true;
RefreshData();
LoadCboData();
DtpReleaseDate.Format = DateTimePickerFormat.Custom;
DtpReleaseDate.CustomFormat = "yyyy-MM-dd";
}
private void DgvResult_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
{
DgvResult.ClearSelection();
}
private void BtnNew_Click(object sender, EventArgs e)
{
ClearInputs();
}
private void BtnSave_Click(object sender, EventArgs e)
{
if (CheckValidation() != true)
{
return;
}
SaveData();
RefreshData();
ClearInputs();
}
private void BtnDel_Click(object sender, EventArgs e)
{
if (isNew == true)
{
MessageBox.Show("삭제할 데이터를 선택하세요", "오류", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
using (MySqlConnection conn = new MySqlConnection(Helpers.Commons.ConnString))
{
if(conn.State==ConnectionState.Closed)
{
conn.Open();
}
string strChkQuery = "SELECT COUNT(*) FROM rentaltbl WHERE bookIdx = @bookIdx";
MySqlCommand chkCmd = new MySqlCommand(strChkQuery, conn);
MySqlParameter prmBookIdx = new MySqlParameter("@bookIdx", TxtBookIdx.Text);
chkCmd.Parameters.Add(prmBookIdx);
var result = chkCmd.ExecuteScalar();
if(result.ToString()!="0")
{
MessageBox.Show("이미 대여중인 책입니다.", "삭제", MessageBoxButtons.OK, MessageBoxIcon.Information);
return;
}
}
if (MessageBox.Show(this, "삭제하시겠습니까?", "삭제", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
{
return;
}
DeleteData();
RefreshData();
ClearInputs();
}
private void DgvResult_CellClick(object sender, DataGridViewCellEventArgs e)
{
if (e.RowIndex > -1)
{
var selData = DgvResult.Rows[e.RowIndex];
TxtBookIdx.Text = selData.Cells[0].Value.ToString();
TxtAuthor.Text = selData.Cells[1].Value.ToString();
CboDivision.SelectedValue = selData.Cells[2].Value;
TxtNames.Text = selData.Cells[4].Value.ToString();
DtpReleaseDate.Value = (DateTime)selData.Cells[5].Value;
TxtISBN.Text= selData.Cells[6].Value.ToString();
NudPrice.Value = (Decimal)selData.Cells[7].Value;
isNew = false;
}
}
#endregion
#region <커스텀 메서드>
private void RefreshData()
{
try
{
using (MySqlConnection conn = new MySqlConnection(Helpers.Commons.ConnString))
{
if (conn.State == ConnectionState.Closed)
{
conn.Open();
}
var SelQuery = @"SELECT b.bookIdx,
b.Author,
b.Division,
d.Names AS DivNames,
b.Names,
b.ReleaseDate,
b.ISBN,
b.Price
FROM bookstbl As b
INNER JOIN divtbl AS d
on b.Division=d.Division
ORDER BY b.bookIdx ASC";
MySqlDataAdapter adapter = new MySqlDataAdapter(SelQuery, conn);
DataSet ds = new DataSet();
adapter.Fill(ds, "bookstbl");
DgvResult.DataSource = ds;
DgvResult.DataMember = "bookstbl";
DgvResult.Columns[0].HeaderText = "번호";
DgvResult.Columns[1].HeaderText = "저자명";
DgvResult.Columns[2].HeaderText = "책장르";
DgvResult.Columns[3].HeaderText = "책장르";
DgvResult.Columns [4].HeaderText = "책제목";
DgvResult.Columns[5].HeaderText = "출판일자";
DgvResult.Columns[6].HeaderText = "ISBN";
DgvResult.Columns[7].HeaderText = "책가격";
DgvResult.Columns[0].Width = 55;
DgvResult.Columns[2].Visible = false;
DgvResult.Columns[5].Width = 80;
DgvResult.Columns[7].Width = 80;
DgvResult.Columns[0].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
DgvResult.Columns[5].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
DgvResult.Columns[7].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
}
}
catch (Exception ex)
{
MessageBox.Show($"RefreshData() 비정상적 오류 : {ex.Message}", "오류", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ClearInputs()
{
TxtBookIdx.Text = TxtAuthor.Text = string.Empty;
TxtNames.Text = TxtISBN.Text = string.Empty;
CboDivision.SelectedIndex = -1;
DtpReleaseDate.Value = DateTime.Now;
NudPrice.Value = 0;
TxtAuthor.Focus();
isNew = true;
}
private bool CheckValidation()
{
var result = true;
var errorMsg = string.Empty;
if (string.IsNullOrEmpty(TxtAuthor.Text))
{
result = false;
errorMsg += "※ 저자명을 입력하세요\r\n";
}
if (CboDivision.SelectedIndex<0)
{
result = false;
errorMsg += "※ 장르를 선택하세요\r\n";
}
if (string.IsNullOrEmpty(TxtNames.Text))
{
result = false;
errorMsg += "※ 책제목을 입력하세요\r\n";
}
if (DtpReleaseDate.Value==null)
{
result = false;
errorMsg += "※ 출판일자를 선택하세요\r\n";
}
if (result == false)
{
MessageBox.Show(errorMsg, "오류", MessageBoxButtons.OK, MessageBoxIcon.Error);
return result;
}
else
{
return result;
}
}
private void SaveData()
{
try
{
using (MySqlConnection conn = new MySqlConnection(Helpers.Commons.ConnString))
{
if (conn.State == ConnectionState.Closed)
{
conn.Open();
}
var query = "";
if (isNew)
{
query = @"INSERT INTO bookstbl
(Author,
Division,
Names,
ReleaseDate,
ISBN,
Price)
VALUES
(@Author,
@Division,
@Names,
@ReleaseDate,
@ISBN,
@Price)";
}
else
{
query = @"UPDATE bookstbl
SET
Author = @Author,
Division = @Division,
Names = @Names,
ReleaseDate = @ReleaseDate,
ISBN = @ISBN,
Price = @Price
WHERE bookIdx = @bookIdx";
}
MySqlCommand cmd = new MySqlCommand(query, conn);
MySqlParameter prmAuthor = new MySqlParameter("@Author", TxtAuthor.Text);
MySqlParameter prmDivision = new MySqlParameter("@Division", CboDivision.SelectedValue.ToString());
MySqlParameter prmNames = new MySqlParameter("@Names", TxtNames.Text);
MySqlParameter prmReleaseDate = new MySqlParameter("@ReleaseDate", DtpReleaseDate.Value);
MySqlParameter prmISBN = new MySqlParameter("@ISBN", TxtISBN.Text);
MySqlParameter prmPrice = new MySqlParameter("@Price", NudPrice.Value);
cmd.Parameters.Add(prmAuthor);
cmd.Parameters.Add(prmDivision);
cmd.Parameters.Add(prmNames);
cmd.Parameters.Add(prmReleaseDate);
cmd.Parameters.Add(prmISBN);
cmd.Parameters.Add(prmPrice);
if (isNew == false)
{
MySqlParameter prmBookIdx = new MySqlParameter("@bookIdx", TxtBookIdx.Text);
cmd.Parameters.Add(prmBookIdx);
}
var result = cmd.ExecuteNonQuery();
if (result != 0)
{
MessageBox.Show("저장 성공!", "저장", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
MessageBox.Show("저장실패!", "저장", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
catch (Exception ex)
{
MessageBox.Show($"SaveData() 비정상적 오류 : {ex.Message}", "오류", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void DeleteData()
{
try
{
using (MySqlConnection conn = new MySqlConnection(Helpers.Commons.ConnString))
{
if (conn.State == ConnectionState.Closed)
{
conn.Open();
}
var query = @"DELETE FROM bookstbl
WHERE bookIdx = @bookidx";
MySqlCommand cmd = new MySqlCommand(query, conn);
MySqlParameter prmBookIdx = new MySqlParameter("@bookIdx", TxtBookIdx.Text);
cmd.Parameters.Add(prmBookIdx);
var result = cmd.ExecuteNonQuery();
if (result != 0)
{
MessageBox.Show("삭제 성공!", "삭제", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
MessageBox.Show("삭제실패!", "삭제", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
catch (Exception ex)
{
MessageBox.Show($"DeleteData() 비정상적 오류 : {ex.Message}", "오류", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void LoadCboData()
{
try
{
using(MySqlConnection conn = new MySqlConnection(Commons.ConnString))
{
if(conn.State== ConnectionState.Closed)
{
conn.Open();
}
var query = "SELECT Division, Names From divtbl";
MySqlCommand cmd = new MySqlCommand(query, conn);
MySqlDataReader reader = cmd.ExecuteReader();
var temp = new Dictionary<string, string>();
while (reader.Read())
{
temp.Add(reader[0].ToString(), reader[1].ToString());
}
CboDivision.DataSource = new BindingSource(temp, null);
CboDivision.DisplayMember = "Value";
CboDivision.ValueMember = "Key";
CboDivision.SelectedIndex = -1;
}
}
catch (Exception ex)
{
MessageBox.Show($"LoadCboData() 비정상적 오류 : {ex.Message}", "오류", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
#endregion
}
}
DB(usertbl/divtbl/bookstbl/rentaltbl)
usertbl
divtbl
bookstbl
rentaltbl
실행화면
초기화면
책 장르 관리
책 정보 관리