C# 포트폴리오 도전기(1-7. 렌탈 페이지 구현 및 v1 완성)

min seung moon·2021년 8월 24일
0

C# 포트폴리오

목록 보기
8/10
post-custom-banner

1. 렌탈 페이지 구현 및 v1 완성

  • v2가 있을지 모르겠지만 일단 처음 생각한 대로 구현은 완료 하였습니다!
    • 100% 만족하느냐하면 그거는 아니겠죠 앞으로 공부해나가면서 바꾸고 수정할게 넘치지만 대략적인 부분은 일단락 되었습니다
    • 렌탈 페이지를 만들면서 어제한 도서 페이지도 수정을 했어요!
      • 도서페이지 등록 시 책 렌탈과 비고 선택하는게 있었는데 사용자를 따로 입력하는게 없으니 삭제했습니다
      • 그리고 렌탈 테이블에는 사용자 번호 추가했구요!

2. DB Table & Procedure

01. Book_Book_Rental Table

-- 책렌탈 테이블
CREATE TABLE Book_Book_Rental(
	user_no		INT			NULL
	,book_no	INT			NULL
	,book_title	NVARCHAR(30)		NULL
	,rental_date	DATETIME		NULL
	,return_date	DATETIME		NULL
);

02. BOOK_RENTAL_S1

  • 현재 렌탈 중인 상태 조회
USE [BookManagement]
GO
/****** Object:  StoredProcedure [dbo].[BOOK_RENTAL_S1]    Script Date: 2021-08-24 오후 3:34:23 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<문민승>
-- Create date: <2021.08.24>
-- Description:	<도서관리프로그램, 렌탈 리스트 조회>
-- =============================================
ALTER PROCEDURE [dbo].[BOOK_RENTAL_S1]
AS
BEGIN
	SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
	
	SELECT		r.user_no as '사용자번호', i.user_name as '사용자이름', r.book_no as '도서번호'
				,r.book_title as '도서명', r.rental_date as '렌탈날짜', r.return_date as '반납날짜'
	FROM		Book_Book_Rental	r
	INNER JOIN	Book_User_Info		i
	ON			r.user_no = i.user_no
	WHERE		r.return_date is null;
END

03. BOOK_RENTAL_S2

  • 반납일이 지난 연체자 조회
USE [BookManagement]
GO
/****** Object:  StoredProcedure [dbo].[BOOK_RENTAL_S2]    Script Date: 2021-08-24 오후 3:37:53 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<문민승>
-- Create date: <2021.08.24>
-- Description:	<도서관리프로그램, 연체자 리스트 조회>
-- =============================================
ALTER PROCEDURE [dbo].[BOOK_RENTAL_S2]
AS
BEGIN
	SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
	
	SELECT			r.user_no as '사용자번호', i.user_name as '사용자이름', r.book_no as '도서번호'
					,r.book_title as '도서명', r.rental_date as '렌탈날짜'
	FROM			Book_Book_Rental	r
	INNER JOIN		Book_User_Info		i
	ON				r.user_no = i.user_no
	WHERE			r.return_date is null
	AND				(select DATEADD(dd, 7, r.rental_date)) < GETDATE();
END

04. BOOK_RENTAL_S3

  • 렌탈 등록 시 도서 페이지 조회
USE [BookManagement]
GO
/****** Object:  StoredProcedure [dbo].[BOOK_RENTAL_S3]    Script Date: 2021-08-24 오후 3:38:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<문민승>
-- Create date: <2021.08.24>
-- Description:	<도서관리프로그램, 렌탈페이지, 도서정보 조회>
-- =============================================
ALTER PROCEDURE [dbo].[BOOK_RENTAL_S3]
	@BOOK_NO	INT
AS
BEGIN
	SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
	
	IF NOT EXISTS
	(
		SELECT		I.book_title, book_writer, book_description, book_saveImagePath 
		FROM		Book_Book_Info I
		INNER JOIN	Book_Book_State S
		ON			I.book_no = S.book_no
		WHERE		I.book_no = @BOOK_NO
		AND			S.book_rental = 1
	)
	BEGIN
		RAISERROR('데이터가 없습니다.',16,1)
		RETURN
	END

	SELECT		I.book_title, book_writer, book_description, book_saveImagePath 
	FROM		Book_Book_Info I
	INNER JOIN	Book_Book_State S
	ON			I.book_no = S.book_no
	WHERE		I.book_no = @BOOK_NO
	AND			S.book_rental = 1;
END

05. BOOK_RENTAL_S4

  • 렌탈 등록 시, 사용자 정보 조회
USE [BookManagement]
GO
/****** Object:  StoredProcedure [dbo].[BOOK_RENTAL_S4]    Script Date: 2021-08-24 오후 3:38:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<문민승>
-- Create date: <2021.08.24>
-- Description:	<도서관리프로그램, 렌탈페이지, 사용자정보 조회>
-- =============================================
ALTER PROCEDURE [dbo].[BOOK_RENTAL_S4]
	@USER_NO	INT
AS
BEGIN
	SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
	
	IF NOT EXISTS
	(
		SELECT		I.user_name, L.user_id, G.grade_name, CONVERT(char(10), L.register_date, 102) as register_date, I.user_address
		FROM		Book_User_Info I
		INNER JOIN	Book_User_LogIn L
		ON			I.user_no = L.user_no
		INNER JOIN	Book_User_Grade G
		ON			L.grade_no = G.grade_no
		WHERE		I.user_no = @USER_NO
	)
	BEGIN
		RAISERROR('데이터가 없습니다.',16,1)
		RETURN
	END


	SELECT		I.user_name, L.user_id, G.grade_name, CONVERT(char(10), L.register_date, 102) as register_date, I.user_address
	FROM		Book_User_Info I
	INNER JOIN	Book_User_LogIn L
	ON			I.user_no = L.user_no
	INNER JOIN	Book_User_Grade G
	ON			L.grade_no = G.grade_no
	WHERE		I.user_no = @USER_NO;
END

06. BOOK_RENTAL_S5

  • 조회한 책이 렌탈 중인지 확인
USE [BookManagement]
GO
/****** Object:  StoredProcedure [dbo].[BOOK_RENTAL_S5]    Script Date: 2021-08-24 오후 3:38:43 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<문민승>
-- Create date: <2021.08.24>
-- Description:	<도서관리프로그램, 특정 도서 렌탈 상태 조회>
-- =============================================
ALTER PROCEDURE [dbo].[BOOK_RENTAL_S5]
	@BOOK_NO	INT
AS
BEGIN
	SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
	
	IF NOT EXISTS
	(
		SELECT * FROM Book_Book_State WHERE book_no = @BOOK_NO AND book_rental= 2
	)
	BEGIN
		RAISERROR('데이터가 없습니다.',16,1)
		RETURN
	END


	SELECT		R.user_no, I.user_name, R.book_no, R.book_title, CONVERT(char(10), R.rental_date, 102) AS rental_date
	FROM		Book_Book_Rental R
	INNER JOIN	Book_User_Info I
	ON			R.user_no = I.user_no
	WHERE		book_no = @BOOK_NO;


END

07. BOOK_RENTAL_S6

  • 모든 렌탈 기록 확인
USE [BookManagement]
GO
/****** Object:  StoredProcedure [dbo].[BOOK_RENTAL_S6]    Script Date: 2021-08-24 오후 3:38:56 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<문민승>
-- Create date: <2021.08.24>
-- Description:	<도서관리프로그램, 렌탈 모든 기록 리스트>
-- =============================================
ALTER PROCEDURE [dbo].[BOOK_RENTAL_S6]
AS
BEGIN
	SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
	
	SELECT		r.user_no as '사용자번호', i.user_name as '사용자이름', r.book_no as '도서번호'
				,r.book_title as '도서명', r.rental_date as '렌탈날짜', r.return_date as '반납날짜'
	FROM		Book_Book_Rental	r
	INNER JOIN	Book_User_Info		i
	ON			r.user_no = i.user_no;
END

08. BOOK_RENTAL_I1

  • 렌탈 등록
USE [BookManagement]
GO
/****** Object:  StoredProcedure [dbo].[BOOK_RENTAL_I1]    Script Date: 2021-08-24 오후 3:39:15 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<문민승>
-- Create date: <2021.08.24>
-- Description:	<도서관리프로그램, 렌탈등록>
-- =============================================
ALTER PROCEDURE [dbo].[BOOK_RENTAL_I1]
	@USER_NO		INT
	,@BOOK_NO		INT
	,@BOOK_TITLE	NVARCHAR(30)
AS
BEGIN
	SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
	
	INSERT INTO Book_Book_Rental(user_no, book_no, book_title, rental_date)
	VALUES(@USER_NO, @BOOK_NO, @BOOK_TITLE, GETDATE());

	UPDATE Book_Book_State SET book_rental = 2 WHERE book_no = @BOOK_NO;
	
	UPDATE Book_Book_Info SET book_rentalcounts = book_rentalcounts + 1 WHERE book_no = @BOOK_NO;
END

09. BOOK_RENTAL_U1

  • 반납으로 렌탈 상태 수정
USE [BookManagement]
GO
/****** Object:  StoredProcedure [dbo].[BOOK_RENTAL_U1]    Script Date: 2021-08-24 오후 3:39:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<문민승>
-- Create date: <2021.08.24>
-- Description:	<도서관리프로그램, 도서 렌탈 반납>
-- =============================================
ALTER PROCEDURE [dbo].[BOOK_RENTAL_U1]
	@USER_NO		INT
	,@BOOK_NO		INT
AS
BEGIN
	SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
	
	UPDATE Book_Book_Rental SET return_date = GETDATE() WHERE user_no = @USER_NO AND book_no = @BOOK_NO;
	UPDATE Book_Book_State SET book_rental = 1 WHERE book_no = @BOOK_NO;
END

10. BOOK_BOOK_S6

  • 메인화면에 보여줄 도서 정보 랜덤으로 조회
USE [BookManagement]
GO
/****** Object:  StoredProcedure [dbo].[BOOK_BOOK_S6]    Script Date: 2021-08-24 오후 3:45:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<문민승>
-- Create date: <2021.08.24>
-- Description:	<도서관리프로그램, 메인화면에 보여줄 랜덤한  정보>
-- =============================================
ALTER PROCEDURE [dbo].[BOOK_BOOK_S6]
AS
BEGIN
	SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
	
	SELECT		TOP 1 book_no, book_title, book_writer, category_name, book_description, book_rentalcounts, book_saveImagePath
	FROM		Book_Book_Info I
	INNER JOIN	Book_Book_Category C
	ON			I.book_category = C.category_no
	ORDER BY	NEWID();
END

3. Book 수정

01. BookAddForm.cs

  • 책 상태 combobox는 삭제했습니다
    • 대신 코드 내부에서는 무조건 1을 넘기도록 했습니다
      • 1은 비고 입니다
      • 삭제하면 에러가 뜨니 그 부분만 수정하면 됩니다
using BookManagementProgram.Model;
using BookManagementProgram.Repository;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace BookManagementProgram.BookControls
{
    public partial class BookAddForm : Form
    {
        BookRepository bookRepository = null;
        public BookAddForm()
        {
            InitializeComponent();

            bookRepository = new BookRepository();
            this.StartPosition = FormStartPosition.CenterParent;

            // 카테고리 콤보 박스
            book_category_cmb.DataSource = new BindingSource(bookRepository.GetCategoryList(), null);
            book_category_cmb.DisplayMember = "Key";
            book_category_cmb.ValueMember = "Value";
            // 위치 콤보 박스
            book_location_cmb.DataSource = new BindingSource(bookRepository.GetBookLocationList(), null);
            book_location_cmb.DisplayMember = "Key";
            book_location_cmb.ValueMember = "Value";
        }

        // 취소 버튼
        private void cancel_btn_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        // 도서 등록
        private void add_book_btn_Click(object sender, EventArgs e)
        {
            if(CheckInput())
            {
                Book book = CreateBookInstance();
                if (bookRepository.AddBook(book))
                {
                    MessageBox.Show("도서 등록에 성공하셨습니다.");
                    this.Close();
                    return;
                }
                MessageBox.Show("도서 등록에 실패하셨습니다.");
            }
        }


        // Book 객체 생성
        private Book CreateBookInstance()
        {
            Book book = new Book();
            book.bookTitle = book_title_txt.Text;
            book.bookWriter = book_writer_txt.Text;
            book.bookCategory_no = (int)book_category_cmb.SelectedValue;
            book.bookDescription = book_description_txt.Text;
            book.bookPrice = Convert.ToInt32(book_price_txt.Text);
            book.bookCompany = book_company_txt.Text;
            book.bookDate = book_date_txt.Text;
            book.bookPages = Convert.ToInt32(book_pages_txt.Text);
            book.bookOriginalImagePath = book_image_txt.Text;
            book.bookSavenameImaegPath = SaveBookImageFIle();
            book.bookLocationNo = (int)book_location_cmb.SelectedValue;
            book.bookRentalNo = 1;

            return book;
        }

        // 텍스트박스 입력 확인
        private bool CheckInput()
        {
            bool check = false;

            if (string.IsNullOrEmpty(book_title_txt.Text))
            {
                MessageBox.Show("책 제목을 입력해주세요.");
                book_title_txt.Focus();
            }
            else if (string.IsNullOrEmpty(book_writer_txt.Text))
            {
                MessageBox.Show("책 저자를 입력해주세요.");
                book_writer_txt.Focus();
            }
            else if (string.IsNullOrEmpty(book_description_txt.Text))
            {
                MessageBox.Show("도서 설명을 입력해주세요.");
                book_description_txt.Focus();
            }
            else if (string.IsNullOrEmpty(book_price_txt.Text) || CheckNumeric(book_price_txt.Text))
            {
                MessageBox.Show("가격을 입력해주세요.");
                book_price_txt.Focus();
            }
            else if (string.IsNullOrEmpty(book_company_txt.Text))
            {
                MessageBox.Show("출판사를 입력해주세요.");
                book_company_txt.Focus();
            }
            else if (string.IsNullOrEmpty(book_date_txt.Text) || CheckDatePattern(book_date_txt.Text))
            {
                MessageBox.Show("출판날짜를 입력해주세요.(2021.01.01)");
                book_date_txt.Focus();
            }
            else if (string.IsNullOrEmpty(book_pages_txt.Text) || CheckNumeric(book_pages_txt.Text))
            {
                MessageBox.Show("총 페이지 수를 입력해주세요.");
                book_pages_txt.Focus();
            }
            else if (string.IsNullOrEmpty(book_image_txt.Text))
            {
                MessageBox.Show("이미지를 선택해주세요.");
                book_image_btn.Focus();
            }
            else
            {
                check = true;
            }

            return check;
        }


        // 출판일 확인 정규식
        private bool CheckDatePattern(string date)
        {
            string pattern = @"^(1[0-9][0-9][0-9]|20\d{2})\.(0[0-9]|1[0-2])\.(0[1-9]|[1-2][0-9]|3[0-1])$";
            if (!Regex.IsMatch(date, pattern))
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        // 숫자인지 확인
        private bool CheckNumeric(string value)
        {
            int result = -1;
            if(Int32.TryParse(value, out result))
            {
                if(result > 0)
                {
                    return false;
                }
            }
            return true;
        }

        // 책 이미지 불러오기 버튼
        private void book_image_btn_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.Title = "이미지 불러오기";
            openFileDialog.FileName = "";
            openFileDialog.Filter = "Image files (*.jpg, *.jpeg, *.jpe, *.jfif, *.png) | *.jpg; *.jpeg; *.jpe; *.jfif; *.png";
            book_image_txt.Text = string.Empty;

            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                book_image_txt.Text = openFileDialog.FileName;
                pictureBox1.Image = new Bitmap(openFileDialog.FileName);
                pictureBox1.SizeMode = PictureBoxSizeMode.Zoom;
            }
        }

        // 이미지 파일 저장
        private string SaveBookImageFIle()
        {
            string dir = @"C:\Users\jjh\Desktop\mms\BookManagerForm\BookImages";
            Image image = Image.FromFile(book_image_txt.Text);
            bool bExist = true;
            int fileCount = 0;
            string fileName = string.Empty;
            string dirMapPath = string.Empty;

            if (image != null)
            {
                fileName = book_image_txt.Text.Split('\\').Last();
                string strName = fileName.Substring(0, fileName.LastIndexOf("."));
                string strExt = fileName.Substring(fileName.LastIndexOf("."));
                while (bExist)
                {
                    dirMapPath = dir;
                    string pathCombine = System.IO.Path.Combine(dirMapPath, fileName);
                    if (System.IO.File.Exists(pathCombine))
                    {
                        fileCount++;
                        fileName = $"{strName}({fileCount}){strExt}";
                    }
                    else
                    {
                        bExist = false;
                    }
                }
                image.Save($@"{dir}\{fileName}");
                MessageBox.Show("이미지 저장이 되었습니다");
            }
            return $@"{dir}\{fileName}";
        }
    }
}

02. BookSelectForm.cs

  • Controls
    • gridcontrol
      • dock Fill을 top으로 변경했습니다
    • panel
      • dock Fill
    • simplebutton
using BookManagementProgram.Repository;
using DevExpress.XtraGrid.Views.Grid;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace BookManagementProgram.BookControls
{
    public partial class BookSelectForm : Form
    {
        BookRepository bookRepository = null;
        public BookSelectForm()
        {
            InitializeComponent();

            bookRepository = new BookRepository();

            InitGridControl();
            this.gridControl1.DataSource = bookRepository.GetAllBooks();
        }

        private void InitGridControl()
        {
            GridView gv = this.gridControl1.MainView as GridView;
            gv.OptionsView.ShowGroupPanel = false;
            gv.OptionsBehavior.Editable = false;
        }

        private void simpleButton1_Click(object sender, EventArgs e)
        {
            SaveFileDialog saveFileDialog = new SaveFileDialog();
            saveFileDialog.FileName = "도서기록";
            saveFileDialog.Filter = "Excel |*.xlsx";
            if (saveFileDialog.ShowDialog() == DialogResult.OK)
            {
                string path = saveFileDialog.FileName;
                gridControl1.ExportToXlsx(path);
                Process.Start(path);
            }
        }
    }
}


4. User Controls 수정

01. UserSelectForm.cs

  • BookSelectForm과 동일합니다
using BookManagementProgram.Repository;
using DevExpress.XtraGrid.Views.Grid;
using System.Diagnostics;
using System.Windows.Forms;

namespace BookManagementProgram.UserControls
{
    public partial class UserSelectForm : Form
    {
        BookUserRepository userRepository = null;

        public UserSelectForm()
        {
            InitializeComponent();
            userRepository = new BookUserRepository();

            InitGridControl();
            this.gridControl1.DataSource = userRepository.GetAllUsers();
        }

        private void InitGridControl()
        {
            GridView gv = this.gridControl1.MainView as GridView;
            gv.OptionsView.ShowGroupPanel = false;
            gv.OptionsBehavior.Editable = false;
        }

        private void simpleButton1_Click(object sender, System.EventArgs e)
        {
            SaveFileDialog saveFileDialog = new SaveFileDialog();
            saveFileDialog.FileName = "사용자기록";
            saveFileDialog.Filter = "Excel |*.xlsx";
            if (saveFileDialog.ShowDialog() == DialogResult.OK)
            {
                string path = saveFileDialog.FileName;
                gridControl1.ExportToXlsx(path);
                Process.Start(path);
            }
        }
    }
}

5. Rental Pages

01. Repository / IBookRentalRepository.interface

using BookManagementProgram.Model;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BookManagementProgram.Repository
{
    interface IBookRentalRepository
    {
        DataTable GetAllRental(); // 렌탈 리스트
        DataTable GetAllDelinquent(); // 연체자 리스트
        DataTable GetBookInfo(string bookNo); // 도서정보 검색
        DataTable GetUserInfo(string userNo);// 사용자정보 검색
        bool AddBook(Rental rental); // 렌탈정보등록
        DataTable CheckRentalBook(string bookNo); // 반납 도서 확인
        bool ReturnBook(string userNo, string bookNo);// 반납 정보 등록
        DataTable GetRentalHistory(); // 전체 렌탈 기록 조회
    }
}

02. Repository / BookRentalRepository.cs

using BookManagementProgram.Model;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BookManagementProgram.Repository
{
    class BookRepository : IBookRepository
    {
        private SqlConnection conn = null;
        private SqlCommand cmd = null;
        public static List<Book> bookList = null;

        public BookRepository()
        {
            conn = DBConn.DBConn.getConn();
            cmd = new SqlCommand();
            cmd.Connection = conn;
        }

        // 도서 전체 리스트
        public DataTable GetAllBooks()
        {
            DataTable dt = new DataTable();
            try
            {
                string sql = "EXEC BOOK_Book_S1;";

                cmd.CommandText = sql;
                conn.Open();

                // 데이터 출력
                using (SqlDataReader SR = cmd.ExecuteReader())
                {
                    dt.Load(SR);
                }
                return dt;
            }
            catch (SqlException e)
            {
                return dt;
            }
            finally
            {
                conn.Close();
            }
        }

        // 카테고리 리스트
        public Dictionary<string, object> GetCategoryList()
        {
            Dictionary<string, object> dic = new Dictionary<string, object>();
            try
            {
                string sql = "EXEC BOOK_BOOK_S2;";

                cmd.CommandText = sql;
                conn.Open();

                // 데이터 출력
                using (SqlDataReader SR = cmd.ExecuteReader())
                {
                    while (SR.Read())
                    {
                        dic.Add(SR[1].ToString(), (int)SR[0]);
                    }
                }
                return dic;
            }
            catch (SqlException e)
            {
                return dic;
            }
            finally
            {
                conn.Close();
            }
        }

        // 책 위치 리스트
        public Dictionary<string, object> GetBookLocationList()
        {
            Dictionary<string, object> dic = new Dictionary<string, object>();
            try
            {
                string sql = "EXEC BOOK_BOOK_S3;";

                cmd.CommandText = sql;
                conn.Open();

                // 데이터 출력
                using (SqlDataReader SR = cmd.ExecuteReader())
                {
                    while (SR.Read())
                    {
                        dic.Add(SR[1].ToString(), (int)SR[0]);
                    }
                }
                return dic;
            }
            catch (SqlException e)
            {
                return dic;
            }
            finally
            {
                conn.Close();
            }
        }

        // 책 렌탈 상태 리스트
        public Dictionary<string, object> GetBookRentalStateList()
        {
            Dictionary<string, object> dic = new Dictionary<string, object>();
            try
            {
                string sql = "EXEC BOOK_BOOK_S4;";

                cmd.CommandText = sql;
                conn.Open();

                // 데이터 출력
                using (SqlDataReader SR = cmd.ExecuteReader())
                {
                    while (SR.Read())
                    {
                        dic.Add(SR[1].ToString(), (int)SR[0]);
                    }
                }
                return dic;
            }
            catch (SqlException e)
            {
                return dic;
            }
            finally
            {
                conn.Close();
            }
        }

        // 도서 등록
        public bool AddBook(Book book)
        {
            try
            {
                string sql = $@"EXEC	BOOK_Book_I1 @BOOK_TITLE = '{book.bookTitle}'
		                            ,@BOOK_WRITER = '{book.bookWriter}'
		                            ,@BOOK_CATEGORY = {book.bookCategory_no}
		                            ,@BOOK_DESCRIPTION = '{book.bookDescription}'
		                            ,@BOOK_PRICE = {book.bookPrice}
		                            ,@BOOK_COMPANY = '{book.bookCompany}'
		                            ,@BOOK_DATE = '{book.bookDate}'
		                            ,@BOOK_PAGES = {book.bookPages}
		                            ,@BOOK_ORIGINALPATH = '{book.bookOriginalImagePath}'
                                    ,@BOOK_SAVEPATH = '{book.bookSavenameImaegPath}'
		                            ,@BOOK_LOCATION = {book.bookLocationNo}
		                            ,@BOOK_STATE = {book.bookRentalNo};";

                cmd.CommandText = sql;
                conn.Open();

                return cmd.ExecuteNonQuery() > 0 ? true : false;
            }
            catch (SqlException e)
            {
                return false;
            }
            finally
            {
                conn.Close();
            }

        }

        // 도서 조회
        public Book GetBookByNumber(string bookNo)
        {
            Book book = null ;
            try
            {
                string sql = $"EXEC BOOK_BOOK_S5 @BOOK_NO = {bookNo};";

                cmd.CommandText = sql;
                conn.Open();

                // 데이터 출력
                using (SqlDataReader SR = cmd.ExecuteReader())
                {
                    while (SR.Read())
                    {
                        book = new Book();
                        book.bookNo = (int)SR[0];
                        book.bookTitle = SR[1].ToString();
                        book.bookWriter = SR[2].ToString();
                        book.bookCategory_no = (int)SR[3];
                        book.bookDescription = SR[4].ToString();
                        book.bookPrice = (int)SR[5];
                        book.bookCompany = SR[6].ToString();
                        book.bookDate = SR[7].ToString();
                        book.bookPages = (int)SR[8];
                        book.bookOriginalImagePath = SR[9].ToString();
                        book.bookSavenameImaegPath = SR[10].ToString();
                        book.bookRentalNo = (int)SR[11];
                        book.bookLocationNo = (int)SR[12];
                    }
                }
                return book;
            }
            catch (SqlException e)
            {
                return book;
            }
            finally
            {
                conn.Close();
            }
        }

        // 도서 삭제
        public bool DeleteBookByNumber(string bookNo)
        {
            try
            {
                string sql = $"EXEC BOOK_BOOK_D1 @BOOK_NO = {bookNo};";

                cmd.CommandText = sql;
                conn.Open();

                return cmd.ExecuteNonQuery() > 0 ? true : false;
            }
            catch (SqlException e)
            {
                return false;
            }
            finally
            {
                conn.Close();
            }
        }

        // 사용자 정보 수정
        public bool UpdateBookInfo(Book book)
        {
            try
            {
                string sql = $@"EXEC	BOOK_BOOK_U1 @BOOK_NO = {book.bookNo}
                                    ,@BOOK_TITLE = '{book.bookTitle}'
		                            ,@BOOK_WRITER = '{book.bookWriter}'
		                            ,@BOOK_CATEGORY = {book.bookCategory_no}
		                            ,@BOOK_DESCRIPTION = '{book.bookDescription}'
		                            ,@BOOK_PRICE = {book.bookPrice}
		                            ,@BOOK_COMPANY = '{book.bookCompany}'
		                            ,@BOOK_DATE = '{book.bookDate}'
		                            ,@BOOK_PAGES = {book.bookPages}
		                            ,@BOOK_ORIGINALPATH = '{book.bookOriginalImagePath}'
                                    ,@BOOK_SAVEPATH = '{book.bookSavenameImaegPath}'
		                            ,@BOOK_LOCATION = {book.bookLocationNo}
		                            ,@BOOK_STATE = {book.bookRentalNo};";

                cmd.CommandText = sql;
                conn.Open();

                return cmd.ExecuteNonQuery() > 0 ? true : false;
            }
            catch (SqlException e)
            {
                return false;
            }
            finally
            {
                conn.Close();
            }
        }

        // 랜덤하게 1개의 도서 받아오는 메서드
        public DataTable GetRandomBook()
        {
            DataTable dt = null;
            try
            {
                string sql = $"EXEC BOOK_BOOK_S6;";

                cmd.CommandText = sql;
                conn.Open();

                // 데이터 출력
                using (SqlDataReader SR = cmd.ExecuteReader())
                {
                    dt = new DataTable();
                    dt.Load(SR);
                }
                return dt;
            }
            catch (SqlException e)
            {
                return dt;
            }
            finally
            {
                conn.Close();
            }
        }
    }
}

03. Model / Rental.cs

  • 이번에는 모델대신에 DataTable에 Load해서 사용해서 사용은 거의 안하거나 안하지만 일단 만들어 두었습니다
namespace BookManagementProgram.Model
{
    class Rental
    {

        private int user_no;
        private string user_name;
        private int book_no;
        private string book_title;
        private string rental_date;
        private string return_date;

        public int userNo { get { return user_no; } set { user_no = value; } }
        public string userName { get { return user_name; } set { user_name = value; } }
        public int bookNo { get { return book_no; } set { book_no = value; } }
        public string bookTitle { get { return book_title; } set { book_title = value; } }
        public string rentalDate { get { return rental_date; } set { rental_date = value; } }
        public string returnDate { get { return return_date; } set { return_date = value; } }

        public Rental(int user_no, string user_name, int book_no, string book_title, string rental_date, string return_date)
        {
            this.user_no = user_no;
            this.user_name = user_name;
            this.book_no = book_no;
            this.book_title = book_title;
            this.rental_date = rental_date;
            this.return_date = return_date;
        }

        // 렌탈 등록할 때 사용되는 생성자
        public Rental(int user_no, int book_no, string book_title)
        {
            this.user_no = user_no;
            this.book_no = book_no;
            this.book_title = book_title;
        }

        public Rental()
        {
        }
    }
}

04. SelectRentalForm.cs

  • 이름이 Select가 앞에 있는데 만들면서 깜빡해서 그러니 원하시면 바꾸시면 됩니다
  • Controls
    • GridControl
    • Panel
    • simpleButton
using BookManagementProgram.Repository;
using DevExpress.XtraGrid.Views.Grid;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace BookManagementProgram.RentalControls
{
    public partial class SelectRentalForm : Form
    {
        BookRentalRepository rentalRepository = null;
        public SelectRentalForm()
        {
            InitializeComponent();
            rentalRepository = new BookRentalRepository();

            InitGridControl();
            this.gridControl1.DataSource = rentalRepository.GetAllRental();
        }

        private void InitGridControl()
        {
            GridView gv = this.gridControl1.MainView as GridView;
            gv.OptionsView.ShowGroupPanel = false;
            gv.OptionsBehavior.Editable = false;
        }

        private void simpleButton1_Click(object sender, EventArgs e)
        {
            SaveFileDialog saveFileDialog = new SaveFileDialog();
            saveFileDialog.FileName = "렌탈기록";
            saveFileDialog.Filter = "Excel |*.xlsx";
            if (saveFileDialog.ShowDialog() == DialogResult.OK)
            {
                string path = saveFileDialog.FileName;
                gridControl1.ExportToXlsx(path);
                Process.Start(path);
            }
        }
    }
}

05. SelectDelinquentForm.cs

  • 연체자 정보 조회하는 폼입니다
  • Controls
    • GridControl
    • Panel
    • simpleButton
using BookManagementProgram.Repository;
using DevExpress.XtraGrid.Views.Grid;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace BookManagementProgram.RentalControls
{
    public partial class SelectDelinquentForm : Form
    {
        BookRentalRepository rentalRepository = null;
        public SelectDelinquentForm()
        {
            InitializeComponent();
            rentalRepository = new BookRentalRepository();

            InitGridControl();
            this.gridControl1.DataSource = rentalRepository.GetAllDelinquent();
        }

        private void InitGridControl()
        {
            GridView gv = this.gridControl1.MainView as GridView;
            gv.OptionsView.ShowGroupPanel = false;
            gv.OptionsBehavior.Editable = false;
        }

        private void simpleButton1_Click(object sender, EventArgs e)
        {
            SaveFileDialog saveFileDialog = new SaveFileDialog();
            saveFileDialog.FileName = "연체자기록";
            saveFileDialog.Filter = "Excel |*.xlsx";
            if (saveFileDialog.ShowDialog() == DialogResult.OK)
            {
                string path = saveFileDialog.FileName;
                gridControl1.ExportToXlsx(path);
                Process.Start(path);
            }
        }
    }
}

06. SelectRentalHistory.cs

  • Controls
    • GridControl
    • Panel
    • simpleButton
using BookManagementProgram.Repository;
using DevExpress.XtraGrid.Views.Grid;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace BookManagementProgram.RentalControls
{
    public partial class SelectRentalHistory : Form
    {
        BookRentalRepository rentalRepository = null;
        public SelectRentalHistory()
        {
            InitializeComponent();
            rentalRepository = new BookRentalRepository();

            InitGridControl();
            this.gridControl1.DataSource = rentalRepository.GetRentalHistory();
        }

        private void InitGridControl()
        {
            GridView gv = this.gridControl1.MainView as GridView;
            gv.OptionsView.ShowGroupPanel = false;
            gv.OptionsBehavior.Editable = false;
        }

        private void simpleButton1_Click(object sender, EventArgs e)
        {
            SaveFileDialog saveFileDialog = new SaveFileDialog();
            saveFileDialog.FileName = "전체렌탈기록";
            saveFileDialog.Filter = "Excel |*.xlsx";
            if(saveFileDialog.ShowDialog() == DialogResult.OK)
            {
                string path = saveFileDialog.FileName;
                gridControl1.ExportToXlsx(path);
                Process.Start(path);
            }
            
        }
    }
}

07. AddRentalForm.cs

  • 입력하는 부분이 없다보니 코드가 많이 줄었네요
  • 렌탈일과 반납일은 Form이 로드되면 바로 DateTime.now를 활용해서 입력해주시구요
  • 도서와 관련된 텍스트박스는 도서조회 후 입력되도록 사용자도 마찬가지입니다
  • 데이터가 조회된 값이 들어가니 따록 검증할것이 없네요
  • Controls
    • label
    • textbox
      • book_no_txt
      • book_title_txt
      • book_writer_txt
      • book_description_txt
      • user_no_txt
      • user_name_txt
      • user_id_txt
      • user_grade_txt
      • user_registeradte_txt
      • user_address_txt
      • rental_userno_txt
      • rental_bookno_txt
      • rental_date_txt
      • return_userno_txt
    • button
      • book_select_btn
      • user_select_btn
    • groupbox
    • picturebox
    • simplebutton
      • cancel_btn
      • rental_btn
using BookManagementProgram.Model;
using BookManagementProgram.Repository;
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 BookManagementProgram.RentalControls
{
    public partial class AddRentalForm : Form
    {
        DataTable dt = null;
        BookRentalRepository rentalRepository = new BookRentalRepository();

        public AddRentalForm()
        {
            InitializeComponent();

            rental_date_txt.Text = DateTime.Now.ToString("yyyy.MM.dd");
            return_date_txt.Text = DateTime.Now.AddDays(7).ToString("yyyy.MM.dd");
        }

        // 도서 조회버튼
        private void book_select_btn_Click(object sender, EventArgs e)
        {
            if(dt != null) dt = null;
            dt = rentalRepository.GetBookInfo(book_no_txt.Text);
            if(dt == null)
            {
                MessageBox.Show("없는 도서이거나 이미 렌탈된 도서 입니다");
                book_no_txt.Focus();
                return;
            }
            book_no_txt.ReadOnly = true;
            book_title_txt.Text = dt.Rows[0]["book_title"].ToString();
            book_writer_txt.Text = dt.Rows[0]["book_writer"].ToString();
            book_description_txt.Text = dt.Rows[0]["book_description"].ToString();
            pictureBox1.Load(dt.Rows[0]["book_saveImagePath"].ToString());
            pictureBox1.SizeMode = PictureBoxSizeMode.Zoom;
            rental_bookno_txt.Text = book_no_txt.Text;

        }
        // 사용자 조회
        private void user_select_btn_Click(object sender, EventArgs e)
        {
            if (dt != null) dt = null;
            dt = rentalRepository.GetUserInfo(user_no_txt.Text);
            if (dt == null)
            {
                MessageBox.Show("번호를 확인해주세요.");
                user_no_txt.Focus();
                return;
            }
            user_no_txt.ReadOnly = true;
            user_name_txt.Text = dt.Rows[0]["user_name"].ToString();
            user_id_txt.Text = dt.Rows[0]["user_id"].ToString();
            user_grade_txt.Text = dt.Rows[0]["grade_name"].ToString();
            user_registerdate_txt.Text = dt.Rows[0]["register_date"].ToString();
            user_address_txt.Text = dt.Rows[0]["user_address"].ToString();

            rental_userno_txt.Text = user_no_txt.Text;
        }
        // 취소 버튼
        private void cancle_btn_Click(object sender, EventArgs e)
        {
            this.Close();
        }
        // 렌탈 등록 버튼
        private void rental_btn_Click(object sender, EventArgs e)
        {
            if(rentalRepository.AddBook(new Rental(
                Convert.ToInt32(rental_userno_txt.Text)
                , Convert.ToInt32(rental_bookno_txt.Text)
                , book_title_txt.Text
                )))
            {
                MessageBox.Show("정상적으로 등록되었습니다.");
                this.Close();
                return;
            }

            MessageBox.Show("등록에 실패하였습니다.");
        }
    }
}

08. ReturnBookForm.cs

  • 도서 번호를 조회해서 만약 렌탈한거라면 정보가 나타나고 반납버튼으로 반납합니다
  • DB랑 Repository에서 다 해주니 좋네요
  • Controls
    • label
    • textbox
      • book_no_txt
      • user_no_txt
      • user_name_txt
      • book_name_txt
      • rental_date_txt
      • today_txt
    • button
      • select_rental_btn
    • simplebutton
      • cancel_btn
      • return_btn
using BookManagementProgram.Repository;
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 BookManagementProgram.RentalControls
{
    public partial class ReturnBookForm : Form
    {
        BookRentalRepository rentalRepository = null;

        public ReturnBookForm()
        {
            InitializeComponent();
            rentalRepository = new BookRentalRepository();
        }

        // 취소 버튼
        private void cancel_btn_Click(object sender, EventArgs e)
        {
            this.Close ();
        }

        // 반납 버튼
        private void return_btn_Click(object sender, EventArgs e)
        {
            if (rentalRepository.ReturnBook(
                    user_no_txt.Text
                    , book_no_txt.Text
                ))
            {
                MessageBox.Show("정상적으로 반납되었습니다.");
                this.Close();
                return;
            }
            MessageBox.Show("반납에 실패하였습니다");
        }

        // 조회 버튼
        private void select_rental_btn_Click(object sender, EventArgs e)
        {
            DataTable dt = rentalRepository.CheckRentalBook(book_no_txt.Text);
            if(dt == null)
            {
                MessageBox.Show("도서 번호를 확인해주세요.");
                book_no_txt.Focus();
                return;
            }

            book_no_txt.ReadOnly = true;
            user_no_txt.Text = dt.Rows[0]["user_no"].ToString();
            user_name_txt.Text = dt.Rows[0]["user_name"].ToString();
            book_name_txt.Text = dt.Rows[0]["book_title"].ToString();
            rental_date_txt.Text = dt.Rows[0]["rental_date"].ToString();
            today_txt.Text = DateTime.Now.ToString("yyyy.MM.dd");
        }
    }
}

6. Main 수정 및 MainControls 수정

01. BookRepository.cs

  • 랜덤하게 도서 정보를 가져오는 메서드 추가했습니다 *GetRandomBook
using BookManagementProgram.Model;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BookManagementProgram.Repository
{
    class BookRepository : IBookRepository
    {
        private SqlConnection conn = null;
        private SqlCommand cmd = null;
        public static List<Book> bookList = null;

        public BookRepository()
        {
            conn = DBConn.DBConn.getConn();
            cmd = new SqlCommand();
            cmd.Connection = conn;
        }

        // 도서 전체 리스트
        public DataTable GetAllBooks()
        {
            DataTable dt = new DataTable();
            try
            {
                string sql = "EXEC BOOK_Book_S1;";

                cmd.CommandText = sql;
                conn.Open();

                // 데이터 출력
                using (SqlDataReader SR = cmd.ExecuteReader())
                {
                    dt.Load(SR);
                }
                return dt;
            }
            catch (SqlException e)
            {
                return dt;
            }
            finally
            {
                conn.Close();
            }
        }

        // 카테고리 리스트
        public Dictionary<string, object> GetCategoryList()
        {
            Dictionary<string, object> dic = new Dictionary<string, object>();
            try
            {
                string sql = "EXEC BOOK_BOOK_S2;";

                cmd.CommandText = sql;
                conn.Open();

                // 데이터 출력
                using (SqlDataReader SR = cmd.ExecuteReader())
                {
                    while (SR.Read())
                    {
                        dic.Add(SR[1].ToString(), (int)SR[0]);
                    }
                }
                return dic;
            }
            catch (SqlException e)
            {
                return dic;
            }
            finally
            {
                conn.Close();
            }
        }

        // 책 위치 리스트
        public Dictionary<string, object> GetBookLocationList()
        {
            Dictionary<string, object> dic = new Dictionary<string, object>();
            try
            {
                string sql = "EXEC BOOK_BOOK_S3;";

                cmd.CommandText = sql;
                conn.Open();

                // 데이터 출력
                using (SqlDataReader SR = cmd.ExecuteReader())
                {
                    while (SR.Read())
                    {
                        dic.Add(SR[1].ToString(), (int)SR[0]);
                    }
                }
                return dic;
            }
            catch (SqlException e)
            {
                return dic;
            }
            finally
            {
                conn.Close();
            }
        }

        // 책 렌탈 상태 리스트
        public Dictionary<string, object> GetBookRentalStateList()
        {
            Dictionary<string, object> dic = new Dictionary<string, object>();
            try
            {
                string sql = "EXEC BOOK_BOOK_S4;";

                cmd.CommandText = sql;
                conn.Open();

                // 데이터 출력
                using (SqlDataReader SR = cmd.ExecuteReader())
                {
                    while (SR.Read())
                    {
                        dic.Add(SR[1].ToString(), (int)SR[0]);
                    }
                }
                return dic;
            }
            catch (SqlException e)
            {
                return dic;
            }
            finally
            {
                conn.Close();
            }
        }

        // 도서 등록
        public bool AddBook(Book book)
        {
            try
            {
                string sql = $@"EXEC	BOOK_Book_I1 @BOOK_TITLE = '{book.bookTitle}'
		                            ,@BOOK_WRITER = '{book.bookWriter}'
		                            ,@BOOK_CATEGORY = {book.bookCategory_no}
		                            ,@BOOK_DESCRIPTION = '{book.bookDescription}'
		                            ,@BOOK_PRICE = {book.bookPrice}
		                            ,@BOOK_COMPANY = '{book.bookCompany}'
		                            ,@BOOK_DATE = '{book.bookDate}'
		                            ,@BOOK_PAGES = {book.bookPages}
		                            ,@BOOK_ORIGINALPATH = '{book.bookOriginalImagePath}'
                                    ,@BOOK_SAVEPATH = '{book.bookSavenameImaegPath}'
		                            ,@BOOK_LOCATION = {book.bookLocationNo}
		                            ,@BOOK_STATE = {book.bookRentalNo};";

                cmd.CommandText = sql;
                conn.Open();

                return cmd.ExecuteNonQuery() > 0 ? true : false;
            }
            catch (SqlException e)
            {
                return false;
            }
            finally
            {
                conn.Close();
            }

        }

        // 도서 조회
        public Book GetBookByNumber(string bookNo)
        {
            Book book = null ;
            try
            {
                string sql = $"EXEC BOOK_BOOK_S5 @BOOK_NO = {bookNo};";

                cmd.CommandText = sql;
                conn.Open();

                // 데이터 출력
                using (SqlDataReader SR = cmd.ExecuteReader())
                {
                    while (SR.Read())
                    {
                        book = new Book();
                        book.bookNo = (int)SR[0];
                        book.bookTitle = SR[1].ToString();
                        book.bookWriter = SR[2].ToString();
                        book.bookCategory_no = (int)SR[3];
                        book.bookDescription = SR[4].ToString();
                        book.bookPrice = (int)SR[5];
                        book.bookCompany = SR[6].ToString();
                        book.bookDate = SR[7].ToString();
                        book.bookPages = (int)SR[8];
                        book.bookOriginalImagePath = SR[9].ToString();
                        book.bookSavenameImaegPath = SR[10].ToString();
                        book.bookRentalNo = (int)SR[11];
                        book.bookLocationNo = (int)SR[12];
                    }
                }
                return book;
            }
            catch (SqlException e)
            {
                return book;
            }
            finally
            {
                conn.Close();
            }
        }

        // 도서 삭제
        public bool DeleteBookByNumber(string bookNo)
        {
            try
            {
                string sql = $"EXEC BOOK_BOOK_D1 @BOOK_NO = {bookNo};";

                cmd.CommandText = sql;
                conn.Open();

                return cmd.ExecuteNonQuery() > 0 ? true : false;
            }
            catch (SqlException e)
            {
                return false;
            }
            finally
            {
                conn.Close();
            }
        }

        // 사용자 정보 수정
        public bool UpdateBookInfo(Book book)
        {
            try
            {
                string sql = $@"EXEC	BOOK_BOOK_U1 @BOOK_NO = {book.bookNo}
                                    ,@BOOK_TITLE = '{book.bookTitle}'
		                            ,@BOOK_WRITER = '{book.bookWriter}'
		                            ,@BOOK_CATEGORY = {book.bookCategory_no}
		                            ,@BOOK_DESCRIPTION = '{book.bookDescription}'
		                            ,@BOOK_PRICE = {book.bookPrice}
		                            ,@BOOK_COMPANY = '{book.bookCompany}'
		                            ,@BOOK_DATE = '{book.bookDate}'
		                            ,@BOOK_PAGES = {book.bookPages}
		                            ,@BOOK_ORIGINALPATH = '{book.bookOriginalImagePath}'
                                    ,@BOOK_SAVEPATH = '{book.bookSavenameImaegPath}'
		                            ,@BOOK_LOCATION = {book.bookLocationNo}
		                            ,@BOOK_STATE = {book.bookRentalNo};";

                cmd.CommandText = sql;
                conn.Open();

                return cmd.ExecuteNonQuery() > 0 ? true : false;
            }
            catch (SqlException e)
            {
                return false;
            }
            finally
            {
                conn.Close();
            }
        }

        // 랜덤하게 1개의 도서 받아오는 메서드
        public DataTable GetRandomBook()
        {
            DataTable dt = null;
            try
            {
                string sql = $"EXEC BOOK_BOOK_S6;";

                cmd.CommandText = sql;
                conn.Open();

                // 데이터 출력
                using (SqlDataReader SR = cmd.ExecuteReader())
                {
                    dt = new DataTable();
                    dt.Load(SR);
                }
                return dt;
            }
            catch (SqlException e)
            {
                return dt;
            }
            finally
            {
                conn.Close();
            }
        }
    }
}

02. MainControls.cs

  • controls
    • picturebox
    • label
    • textbox
      • book_no_txt
      • book_title_txt
      • book_writer_txt
      • book_category_txt
      • book_description_txt
      • book_rentalcount_txt
using BookManagementProgram.Repository;
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 BookManagementProgram.MainControls
{
    public partial class MainPageForm : Form
    {
        BookRepository bookRepository = null;
        public MainPageForm()
        {
            InitializeComponent();
            bookRepository = new BookRepository();

            DataTable dt = bookRepository.GetRandomBook();

            pictureBox1.Load(dt.Rows[0]["book_saveImagePath"].ToString());
            pictureBox1.SizeMode = PictureBoxSizeMode.Zoom;
            book_no_txt.Text = dt.Rows[0]["book_no"].ToString();
            book_title_txt.Text = dt.Rows[0]["book_title"].ToString();
            book_writer_txt.Text = dt.Rows[0]["book_writer"].ToString();
            book_category_txt.Text = dt.Rows[0]["category_name"].ToString();
            book_description_txt.Text = dt.Rows[0]["book_description"].ToString();
            book_rentalcount_txt.Text = dt.Rows[0]["book_rentalcounts"].ToString();
        }
    }
}

03. Main.cs

  • 홈 페이지에 조회를 홈으로 디자인하고 이름 바꿨습니다
using BookManagementProgram.XtraForm;
using BookManagementProgram.Model;
using  BookManagementProgram.Repository;
using System;
using System.Windows.Forms;
using DevExpress.XtraTabbedMdi;
using System.Reflection;
using BookManagementProgram.UserControls;
using BookManagementProgram.BookControls;
using BookManagementProgram.RentalControls;

namespace BookManagementProgram
{
    public partial class Main : DevExpress.XtraEditors.XtraForm
    {
        User user = BookUserRepository.user;
        XtraTabbedMdiManager mdiManager;

        public Main()
        {
            InitializeComponent();
            this.StartPosition = FormStartPosition.CenterScreen;

            switch(user.authorityNo)
            {
                case 0:
                    user_page.Visible = true;
                    book_page.Visible = true;
                    rental_page.Visible = true;
                    break;
                case 1:
                    book_page.Visible = true;
                    rental_page.Visible = true;
                    break;
                case 2:
                    rental_page.Visible = true;
                    break;
            }
        }
        // 유저 페이지 유저 조회 버튼
        private void user_reset_btn_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            MenuRun("UserSelectForm", user_reset_btn.Hint);
        }

        // 폼 종료
        private void Main_FormClosed(object sender, FormClosedEventArgs e)
        {
            Application.Exit();
        }

        // 폼 종료 버튼
        private void home_close_btn_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            Application.Exit();
        }

        // 비밀번호 변경 버튼
        private void home_changePassword_btn_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            (new FindByPassword()).ShowDialog();
        }

        // 유저 페이지 유저 등록 버튼
        private void user_add_btn_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            (new UserAddForm()).ShowDialog();
        }

        // 유저 페이지 유저 검색 버튼
        private void user_search_btn_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            (new UserSearchForm()).ShowDialog();
        }

        // 도서 페이지 유저 조회 버튼
        private void book_reset_btn_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            MenuRun("BookSelectForm", book_reset_btn.Hint);
        }

        // 도서 추가 버튼
        private void book_add_btn_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            (new BookAddForm()).ShowDialog();
        }

        // 도서 조회 버튼
        private void book_search_btn_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            (new BookSearchForm()).ShowDialog();
        }
        // 렌탈 조회 버튼
        private void rental_reset_btn_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            MenuRun("SelectRentalForm", rental_reset_btn.Hint);
        }

        // 연체자 조회 버튼
        private void overdue_reset_btn_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            MenuRun("SelectDelinquentForm", rental_return_btn.Hint);
        }
        // 렌탈 등록버튼
        private void rental_add_btn_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            (new AddRentalForm()).ShowDialog();
        }
        // 반납 확인 버튼
        private void rental_return_btn_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            (new ReturnBookForm()).ShowDialog();
        }
        // 렌탈 히스토리 폼
        private void rental_log_btn_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            MenuRun("SelectRentalHistory", rental_log_btn.Hint);
        }
        // 홈버튼
        private void home_btn_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            MenuRun("MainPageForm", home_btn.Hint);
        }

        // 메인 폼 로드
        private void Main_Load(object sender, EventArgs e)
        {
            ChildFormAdd();

            MenuRun("MainPageForm", home_btn.Hint);
        }

        // MID Child Form추가
        private void ChildFormAdd()
        {
            mdiManager = new XtraTabbedMdiManager();
            mdiManager.MdiParent = this;
            mdiManager.HeaderButtons = DevExpress.XtraTab.TabButtons.Close;
            mdiManager.HeaderLocation = DevExpress.XtraTab.TabHeaderLocation.Top;
            mdiManager.PageAdded += MdiManager_ChildFormAdd;
            mdiManager.ClosePageButtonShowMode = DevExpress.XtraTab.ClosePageButtonShowMode.InActiveTabPageAndTabControlHeader;
        }


        // MDI 설정
        private void MdiManager_ChildFormAdd(object sender, MdiTabPageEventArgs e)
        {
            XtraMdiTabPage page = e.Page;
        }

        // 첫 로드할때 보여줄 메인 페이지
        private void Home()
        {

            foreach (Form item in this.MdiChildren)
            {
                if (item.Name == "HOME")  //Notice
                {
                    item.Close();
                }
            }

            Assembly asm = Assembly.GetExecutingAssembly();

            Form frm = (Form)asm.CreateInstance(string.Format("{0}.{1}", "BookManagementProgram.MainControls", "MainPageForm"));

            if (frm != null)
            {
                frm.Text = "메인화면";
                frm.MdiParent = this;
                frm.Dock = DockStyle.Fill;
                frm.Show();

            }
        }


        // 메뉴 아이템에 따라 MID Child 생성
        private void MenuRun(string Menu, string FormTitle)
        {
            string nameSpace;

            foreach (Form item in this.MdiChildren)
            {
                if (Menu == item.Name)
                {
                    item.Close();
                }
            }

            Form frm = null;
            if (Menu.Equals("UserSelectForm"))
            {
                nameSpace = "BookManagementProgram.UserControls";
                System.Reflection.Assembly assembly = System.Reflection.Assembly.Load("BookManagementProgram");
                frm = (Form)assembly.CreateInstance(string.Format("{0}.{1}", nameSpace, Menu));
            }
            else if(Menu.Equals("BookSelectForm"))
            {
                nameSpace = "BookManagementProgram.BookControls";
                System.Reflection.Assembly assembly = System.Reflection.Assembly.Load("BookManagementProgram");
                frm = (Form)assembly.CreateInstance(string.Format("{0}.{1}", nameSpace, Menu));
            }
            else if (Menu.Equals("SelectRentalForm"))
            {
                nameSpace = "BookManagementProgram.RentalControls";
                System.Reflection.Assembly assembly = System.Reflection.Assembly.Load("BookManagementProgram");
                frm = (Form)assembly.CreateInstance(string.Format("{0}.{1}", nameSpace, Menu));
            }
            else if (Menu.Equals("SelectDelinquentForm"))
            {
                nameSpace = "BookManagementProgram.RentalControls";
                System.Reflection.Assembly assembly = System.Reflection.Assembly.Load("BookManagementProgram");
                frm = (Form)assembly.CreateInstance(string.Format("{0}.{1}", nameSpace, Menu));
            }
            else if (Menu.Equals("SelectRentalHistory"))
            {
                nameSpace = "BookManagementProgram.RentalControls";
                System.Reflection.Assembly assembly = System.Reflection.Assembly.Load("BookManagementProgram");
                frm = (Form)assembly.CreateInstance(string.Format("{0}.{1}", nameSpace, Menu));
            }
            else if (Menu.Equals("MainPageForm"))
            {
                nameSpace = "BookManagementProgram.MainControls";
                System.Reflection.Assembly assembly = System.Reflection.Assembly.Load("BookManagementProgram");
                frm = (Form)assembly.CreateInstance(string.Format("{0}.{1}", nameSpace, Menu));
            }

            if (frm != null)
            {
                frm.Text = FormTitle;
                frm.MdiParent = this;
                frm.Show();
            }
            else
            {
                MessageBox.Show("개발중이거나 존재하지 않는 화면입니다.", "오류", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
        }

        
    }
}

7. 후기

  • 우와 드디어 마무리했네요
  • 아직 코드가 지저분하지만 그래도 무언가를 완성하는건 기분이 좋네요
  • 구글링도 많이하고 그냥 무작정 쳐보기도 하고 테스트도 많이했네요
  • 앞으로도 이렇게 파이팅해보겠습니다

01. 깜빡했어요!

  • this.StartPosition = FormStartPosition.CenterParent;
  • 이 코드를Rental 페이지의 Add랑 Return 생성자에 초기화해주세요!

https://github.com/minseung-moon/CSharpStudyRepository

profile
아직까지는 코린이!
post-custom-banner

0개의 댓글