첨부 실행 코드는 나눔고딕코딩 폰트를 사용합니다.

728x90
반응형
728x170

TestProject.zip
다운로드

▶ TestDB.sql

CREATE TABLE dbo.Memo
(
    ID            INT           IDENTITY(1, 1) PRIMARY KEY, -- ID
    Title         NVARCHAR(100) NOT NULL,                   -- 제목
    MailAddress   NVARCHAR(100) NULL,                       -- 메일 주소
    [Description] NVARCHAR(500) NOT NULL,                   -- 설명
    WriteDate     DATETIME      DEFAULT(GETDATE()),         -- 작성일
    WriteIP       NVARCHAR(15)  NULL                        -- 작성 IP 주소
)
GO

INSERT INTO dbo.Memo
VALUES
(
    N'메모1',
    N'test@daum.com',
    N'테스트 문자열',
    GetDate(),
    '127.0.0.1'
)
Go

SELECT
    ID
   ,Title
   ,MailAddress
   ,[Description]
   ,WriteDate
   ,WriteIP
FROM dbo.Memo
ORDER BY ID DESC
GO

SELECT
    ID
   ,Title
   ,MailAddress
   ,[Description]
   ,WriteDate
   ,WriteIP
FROM  dbo.Memo
WHERE ID = 1
GO

BEGIN TRANSACTION
    UPDATE dbo.Memo
    SET
        Title         = N'메모1 (수정)',
        MailAddress   = N'test@daum.com',
        [Description] = N'테스트 문자열 (수정)',
        WriteIP       = N'127.0.0.1'
    Where ID = 1
COMMIT TRANSACTION
GO

BEGIN TRANSACTION
    DELETE FROM dbo.Memo
    Where  ID = 10
COMMIT TRAN
GO

SELECT
    ID
   ,Title
   ,MailAddress
   ,[Description]
   ,WriteDate
   ,WriteIP
From  dbo.Memo
Where Title       = '메모1'
Or    MailAddress Like '%test%'
ORDER BY ID DESC
GO

CREATE PROCEDURE dbo.WriteMemo(@Title NVARCHAR(100), @MailAddress NVARCHAR(100), @Description NVARCHAR(500), @WriteIP NVARCHAR(15))
AS
    INSERT INTO dbo.Memo
    (
        Title
       ,MailAddress
       ,[Description]
       ,WriteIP
    )
    Values
    (
        @Title
       ,@MailAddress
       ,@Description
       ,@WriteIP
    )
GO

CREATE PROCEDURE dbo.ListMemo
AS
    SELECT
        ID
       ,Title
       ,MailAddress
       ,[Description]
       ,WriteDate
       ,WriteIP
    FROM dbo.Memo
    ORDER BY ID DESC
GO

CREATE PROCEDURE dbo.ViewMemo(@ID INT)
AS
    SELECT
        ID
       ,Title
       ,MailAddress
       ,[Description]
       ,WriteDate
       ,WriteIP
    FROM  dbo.Memo
    WHERE ID = @ID
GO

CREATE PROCEDURE dbo.UpdateMemo(@Title NVARCHAR(100), @MailAddress NVARCHAR(100), @Description NVARCHAR(150), @ID INT)
AS
BEGIN TRANSACTION
    UPDATE dbo.Memo
    SET
        Title         = @Title
       ,MailAddress   = @MailAddress
       ,[Description] = @Description
    Where ID = @ID
COMMIT TRANSACTION
GO

CREATE PROCEDURE dbo.DeleteMemo(@ID INT)
AS
    DELETE FROM dbo.Memo
    Where  ID = @ID
GO

CREATE PROCEDURE dbo.SearchMemo(@SearchField NVARCHAR(100), @SearchQuery NVARCHAR(100))
AS
    DECLARE @SQL NVARCHAR(1000)

    SET @SQL = '
SELECT
    ID
   ,Title
   ,MailAddress
   ,[Description]
   ,WriteDate
   ,WriteIP
FROM dbo.Memo
WHERE ' + @SearchField + ' LIKE N''%' + @SearchQuery + '%''
ORDER BY ID DESC
'

    EXECUTE SP_EXECUTESQL @SQL
GO

 

728x90

 

▶ MemoModel.cs

using System;

namespace TestProject.Models
{
    /// <summary>
    /// 메모 모델
    /// </summary>
    public class MemoModel
    {
        //////////////////////////////////////////////////////////////////////////////////////////////////// Property
        ////////////////////////////////////////////////////////////////////////////////////////// Public

        #region ID - ID

        /// <summary>
        /// ID
        /// </summary>
        public int ID { get; set; }

        #endregion
        #region 제목 - Title

        /// <summary>
        /// 제목
        /// </summary>
        public string Title { get; set; }

        #endregion
        #region 메일 주소 - MailAddress

        /// <summary>
        /// 메일 주소
        /// </summary>
        public string MailAddress { get; set; }

        #endregion
        #region 설명 - Description

        /// <summary>
        /// 설명
        /// </summary>
        public string Description { get; set; }

        #endregion
        #region 작성일 - WriteDate

        /// <summary>
        /// 작성일
        /// </summary>
        public DateTime WriteDate { get; set; }

        #endregion
        #region 작성 IP - WriteIP

        /// <summary>
        /// 작성 IP
        /// </summary>
        public string WriteIP { get; set; }

        #endregion
    }
}

 

300x250

 

▶ Web.config

<?xml version="1.0" encoding="utf-8"?>
<configuration>
    <system.web>
        <compilation
            targetFramework="4.6"
            debug="true" />
        <httpRuntime targetFramework="4.6" />
    </system.web>
    <connectionStrings>
        <add name="ConnectionString" connectionString="Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=TestDB;Integrated Security=True;" />
    </connectionStrings>
</configuration>

 

▶ ListPage.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="ListPage.aspx.cs" Inherits="TestProject.ListPage" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>데이터베이스 CRUD 작업하기</title>
    </head>
    <body>
        <form id="form" runat="server">
            <div>
                <h3>메모 목록</h3>
                <asp:GridView ID="gridView" runat="server"
                    AutoGenerateColumns="false">
                    <Columns>
                        <asp:BoundField HeaderText="ID"    DataField="ID"    />
                        <asp:BoundField HeaderText="Title" DataField="Title" />
                        <asp:HyperLinkField HeaderText="설명" DataTextField="Description" 
                            DataNavigateUrlFormatString="ViewPage.aspx?ID={0}"
                            DataNavigateUrlFields="ID" />
                        <asp:TemplateField HeaderText="작성일">
                            <ItemTemplate>
                                <%# Eval("WriteDate") %>
                            </ItemTemplate>
                        </asp:TemplateField>
                    </Columns>
                </asp:GridView>
                <hr />
                <asp:HyperLink ID="writeHyperLink" runat="server"
                    NavigateUrl="~/WritePage.aspx">
                    쓰기
                </asp:HyperLink>
                <asp:HyperLink ID="searchHyperLink" runat="server"
                    NavigateUrl="~/SearchPage.aspx">
                    검색
                </asp:HyperLink>
            </div>
        </form>
    </body>
</html>

 

▶ ListPage.aspx.cs

using System;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Web.UI;

namespace TestProject
{
    /// <summary>
    /// 목록 페이지
    /// </summary>
    public partial class ListPage : Page
    {
        //////////////////////////////////////////////////////////////////////////////////////////////////// Method
        ////////////////////////////////////////////////////////////////////////////////////////// Protected

        #region 페이지 로드시 처리하기 - Page_Load(sender, e)

        /// <summary>
        /// 페이지 로드시 처리하기
        /// </summary>
        /// <param name="sender">이벤트 발생자</param>
        /// <param name="e">이벤트 인자</param>
        protected void Page_Load(object sender, EventArgs e)
        {
            string connectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;

            SqlConnection connection = new SqlConnection(connectionString);

            connection.Open();

            SqlCommand command = new SqlCommand("ListMemo", connection);

            command.CommandType = CommandType.StoredProcedure;

            SqlDataAdapter adapter = new SqlDataAdapter(command);

            DataSet dataSet = new DataSet();

            adapter.Fill(dataSet, "Memo");

            this.gridView.DataSource = dataSet;

            this.gridView.DataBind(); 

            connection.Close();
        }

        #endregion
    }
}

 

▶ ViewPage.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="ViewPage.aspx.cs" Inherits="TestProject.ViewPage" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>데이터베이스 CRUD 작업하기</title>
    </head>
    <body>
        <form id="form" runat="server">
            <div>
                <h3>메모</h3>
                번호 : <asp:Label ID="idLabel" runat="server"/><br />
                제목 : <asp:Label ID="titleLabel" runat="server"/><br />
                메일 주소 : <asp:Label ID="mailAddresslabel" runat="server"/><br />
                설명 : <asp:Label ID="descriptionLabel" runat="server"/><br />
                작성일 : <asp:Label ID="writeDateLabel" runat="server"/><br />
                작성 IP : <asp:Label ID="writeIPLabel" runat="server"/><br />
                <hr />
                <asp:HyperLink ID="updateHylerLink" runat="server">수정</asp:HyperLink>
                <asp:HyperLink ID="deleteHyperLink" runat="server">삭제</asp:HyperLink>
                <asp:HyperLink ID="listHyperLink" runat="server" 
                    NavigateUrl="~/ListPage.aspx">
                    목록
                </asp:HyperLink>
            </div>
        </form>
    </body>
</html>

 

▶ ViewPage.aspx.cs

using System;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Web.UI;

namespace TestProject
{
    /// <summary>
    /// 뷰 페이지
    /// </summary>
    public partial class ViewPage : Page
    {
        //////////////////////////////////////////////////////////////////////////////////////////////////// Method
        ////////////////////////////////////////////////////////////////////////////////////////// Protected

        #region 페이지 로드시 처리하기 - Page_Load(sender, e)

        /// <summary>
        /// 페이지 로드시 처리하기
        /// </summary>
        /// <param name="sender">이벤트 발생자</param>
        /// <param name="e">이벤트 인자</param>
        protected void Page_Load(object sender, EventArgs e)
        {
            if(string.IsNullOrEmpty(Request["ID"]))
            {
                Response.Write("잘못된 요청입니다.");

                Response.End();
            }
            else
            {
                DisplayData();

                this.updateHylerLink.NavigateUrl = $"UpdatePage.aspx?ID={Request["ID"]}";
                this.deleteHyperLink.NavigateUrl = $"DeletePage.aspx?ID={Request["ID"]}";
            }
        }

        #endregion

        ////////////////////////////////////////////////////////////////////////////////////////// Private

        #region 데이터 표시하기 - DisplayData()

        /// <summary>
        /// 데이터 표시하기
        /// </summary>
        private void DisplayData()
        {
            string id = Request["ID"];

            string connectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;

            SqlConnection connection = new SqlConnection(connectionString);

            connection.Open();

            SqlCommand command = new SqlCommand("ViewMemo", connection);

            command.CommandType = CommandType.StoredProcedure;

            command.Parameters.Add("ID", SqlDbType.Int);

            command.Parameters["ID"].Value = Convert.ToInt32(id);

            SqlDataReader reader = command.ExecuteReader();

            if(reader.Read())
            {
                this.idLabel.Text          = id;
                this.titleLabel.Text       = reader["Title"      ].ToString();
                this.mailAddresslabel.Text = reader["MailAddress"].ToString();
                this.descriptionLabel.Text = reader["Description"].ToString();
                this.writeDateLabel.Text   = reader["WriteDate"  ].ToString();
                this.writeIPLabel.Text     = reader["WriteIP"    ].ToString();
            }
            else
            {
                Response.Write("존재하지 않는 데이터 입니다.");

                Response.End();
            }

            reader.Close();

            connection.Close(); 
        }

        #endregion
    }
}

 

▶ WritePage.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WritePage.aspx.cs" Inherits="TestProject.WritePage" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>데이터베이스 CRUD 작업하기</title>
    </head>
    <body>
        <form id="form" runat="server">
            <div>
                <h3>메모 쓰기</h3>
                제목 : <asp:TextBox ID="titleTextBox" runat="server" /><br />
                메일 주소 : <asp:TextBox ID="mailAddressTextBox" runat="server" /><br />
                설명 : <asp:TextBox ID="descriptionTextBox" runat="server" /><br />
                <asp:Button ID="writeButton" runat="server"
                    Text="쓰기" 
                    OnClick="writeButton_Click" />
                &nbsp;
                <asp:Button ID="listButton" runat="server"
                    Text="목록" 
                    OnClick="listButton_Click" />
                <hr />
                <asp:Label ID="displayLabel" runat="server" />
            </div>
        </form>
    </body>
</html>

 

▶ WritePage.aspx.cs

using System;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Web.UI;

using TestProject.Models;

namespace TestProject
{
    /// <summary>
    /// 메모 쓰기 페이지
    /// </summary>
    public partial class WritePage : Page
    {
        //////////////////////////////////////////////////////////////////////////////////////////////////// Method
        ////////////////////////////////////////////////////////////////////////////////////////// Protected

        #region 페이지 로드시 처리하기 - Page_Load(sender, e)

        /// <summary>
        /// 페이지 로드시 처리하기
        /// </summary>
        /// <param name="sender">이벤트 발생자</param>
        /// <param name="e">이벤트 인자</param>
        protected void Page_Load(object sender, EventArgs e)
        {
        }

        #endregion
        #region 쓰기 버튼 클릭시 처리하기 - writeButton_Click(sender, e)

        /// <summary>
        /// 쓰기 버튼 클릭시 처리하기
        /// </summary>
        /// <param name="sender">이벤트 발생자</param>
        /// <param name="e">이벤트 인자</param>
        protected void writeButton_Click(object sender, EventArgs e)
        {
            MemoModel memo = new MemoModel();

            memo.Title       = this.titleTextBox.Text;
            memo.MailAddress = this.mailAddressTextBox.Text;
            memo.Description = this.descriptionTextBox.Text;
            memo.WriteDate   = DateTime.Now;
            memo.WriteIP     = Request.UserHostAddress;

            string connectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;

            SqlConnection connection = new SqlConnection(connectionString);

            connection.Open();

            SqlCommand command = new SqlCommand("WriteMemo", connection);

            command.CommandType = CommandType.StoredProcedure;

            command.Parameters.AddWithValue("@Title"       , memo.Title      );
            command.Parameters.AddWithValue("@MailAddress" , memo.MailAddress);
            command.Parameters.AddWithValue("@Description" , memo.Description);
            command.Parameters.AddWithValue("@WriteIP"     , memo.WriteIP    );

            command.ExecuteNonQuery(); 

            connection.Close();

            this.displayLabel.Text = "저장되었습니다.";
        }

        #endregion
        #region 목록 버튼 클릭시 처리하기 - listButton_Click(sender, e)

        /// <summary>
        /// 목록 버튼 클릭시 처리하기
        /// </summary>
        /// <param name="sender">이벤트 발생자</param>
        /// <param name="e">이벤트 인자</param>
        protected void listButton_Click(object sender, EventArgs e)
        {
            Response.Redirect("ListPage.aspx");
        }

        #endregion
    }
}

 

▶ UpdatePage.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="UpdatePage.aspx.cs" Inherits="TestProject.UpdatePage" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>데이터베이스 CRUD 작업하기</title>
    </head>
    <body>
        <form id="form" runat="server">
            <div>
                <h3>메모 수정</h3>
                ID : <asp:Label ID="idLabel" runat="server"/><br />
                제목 : <asp:TextBox ID="titleTextBox" runat="server" /><br />
                메일 주소 : <asp:TextBox ID="mailAddressTextBox" runat="server" /><br />
                설명 : <asp:TextBox ID="descriptionTextBox" runat="server" /><br />
                <asp:Button ID="updateButton" runat="server"
                    Text="수정"
                    OnClick="updateButton_Click" />
                <asp:Button ID="listButton" runat="server"
                    Text="목록"
                    OnClick="listButton_Click" />
            </div>
        </form>
    </body>
</html>

 

▶ UpdatePage.aspx.cs

using System;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Web.UI;

using TestProject.Models;

namespace TestProject
{
    /// <summary>
    /// 수정 페이지
    /// </summary>
    public partial class UpdatePage : Page
    {
        //////////////////////////////////////////////////////////////////////////////////////////////////// Method
        ////////////////////////////////////////////////////////////////////////////////////////// Protected

        #region 페이지 로드시 처리하기 - Page_Load(sender, e)

        /// <summary>
        /// 페이지 로드시 처리하기
        /// </summary>
        /// <param name="sender">이벤트 발생자</param>
        /// <param name="e">이벤트 인자</param>
        protected void Page_Load(object sender, EventArgs e)
        {
            if(string.IsNullOrEmpty(Request["ID"]))
            {
                Response.Write("잘못된 요청입니다.");

                Response.End();
            }
            else
            {
                if(!Page.IsPostBack)
                {
                    DisplayData();
                }
            }
        }

        #endregion
        #region 수정 버튼 클릭시 처리하기 - updateButton_Click(sender, e)

        /// <summary>
        /// 수정 버튼 클릭시 처리하기
        /// </summary>
        /// <param name="sender">이벤트 발생자</param>
        /// <param name="e">이벤트 인자</param>
        protected void updateButton_Click(object sender, EventArgs e)
        {
            MemoModel memo = new MemoModel();

            memo.ID          = Convert.ToInt32(Request["ID"]);
            memo.Title       = this.titleTextBox.Text;
            memo.MailAddress = this.mailAddressTextBox.Text;
            memo.Description = this.descriptionTextBox.Text;

            string connectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;

            SqlConnection connection = new SqlConnection(connectionString);

            connection.Open();

            SqlCommand command = new SqlCommand("UpdateMemo", connection);

            command.CommandType = CommandType.StoredProcedure;

            command.Parameters.AddWithValue("@Title"      , memo.Title      );
            command.Parameters.AddWithValue("@MailAddress", memo.MailAddress);
            command.Parameters.AddWithValue("@Description", memo.Description);
            command.Parameters.AddWithValue("@ID"         , memo.ID         );

            command.ExecuteNonQuery();

            connection.Close();

            Response.Redirect("ViewPage.aspx?ID=" + Request["ID"]); 
        }

        #endregion
        #region 목록 버튼 클릭시 처리하기 - listButton_Click(sender, e)

        /// <summary>
        /// 목록 버튼 클릭시 처리하기
        /// </summary>
        /// <param name="sender">이벤트 발생자</param>
        /// <param name="e">이벤트 인자</param>
        protected void listButton_Click(object sender, EventArgs e)
        {
            Response.RedirectPermanent("ListPage.aspx");
        }

        #endregion

        ////////////////////////////////////////////////////////////////////////////////////////// Private

        #region 데이터 표시하기 - DisplayData()

        /// <summary>
        /// 데이터 표시하기
        /// </summary>
        private void DisplayData()
        {
            string id = Request["ID"];

            string connectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;

            SqlConnection conection = new SqlConnection(connectionString);

            conection.Open();

            SqlCommand command = new SqlCommand("ViewMemo", conection);

            command.CommandType = CommandType.StoredProcedure;

            command.Parameters.Add("ID", SqlDbType.Int);

            command.Parameters["ID"].Value = Convert.ToInt32(id);

            SqlDataReader reader = command.ExecuteReader();

            if(reader.Read())
            {
                this.idLabel.Text            = Request["ID"];
                this.titleTextBox.Text       = reader["Title"      ].ToString();
                this.mailAddressTextBox.Text = reader["MailAddress"].ToString();
                this.descriptionTextBox.Text = reader["Description"].ToString();
            }
            else
            {
                Response.Write("존재하지 않는 데이터 입니다.");

                Response.End();
            }

            reader.Close();

            conection.Close();
        }

        #endregion
    }
}

 

▶ DeletePage.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="DeletePage.aspx.cs" Inherits="TestProject.DeletePage" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>데이터베이스 CRUD 작업하기</title>
    </head>
    <body>
        <form id="form" runat="server">
            <div>
                <h3>메모 삭제</h3>
                <asp:Label ID="idLabel" runat="server" />번 글을 삭제하시겠습니까?
                <asp:Button ID="deleteButton" runat="server"
                    Text="삭제"
                    OnClientClick="return confirm('정말로 삭제하시겠습니까?');"
                    OnClick="deleteButton_Click" />
                <asp:HyperLink ID="listHyperLink" runat="server" 
                    NavigateUrl="~/ListPage.aspx">
                    목록
                </asp:HyperLink>
            </div>
        </form>
    </body>
</html>

 

▶ DeletePage.aspx.cs

using System;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Web.UI;

namespace TestProject
{
    /// <summary>
    /// 삭제 페이지
    /// </summary>
    public partial class DeletePage : Page
    {
        //////////////////////////////////////////////////////////////////////////////////////////////////// Method
        ////////////////////////////////////////////////////////////////////////////////////////// Protected

        #region 페이지 로드시 처리하기 - Page_Load(sender, e)

        /// <summary>
        /// 페이지 로드시 처리하기
        /// </summary>
        /// <param name="sender">이벤트 발생자</param>
        /// <param name="e">이벤트 인자</param>
        protected void Page_Load(object sender, EventArgs e)
        {
            if(string.IsNullOrEmpty(Request["ID"]))
            {
                Response.Write("잘못된 요청입니다.");

                Response.End();
            }
            else
            {
                if(!Page.IsPostBack)
                {
                    this.idLabel.Text = Request["ID"];
                }
            }
        }

        #endregion
        #region 삭제 버튼 클릭시 처리하기 - deleteButton_Click(sender, e)

        /// <summary>
        /// 삭제 버튼 클릭시 처리하기
        /// </summary>
        /// <param name="sender">이벤트 발생자</param>
        /// <param name="e">이벤트 인자</param>
        protected void deleteButton_Click(object sender, EventArgs e)
        {
            string connectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
                
            SqlConnection connection = new SqlConnection(connectionString);

            connection.Open();

            SqlCommand command = new SqlCommand("DeleteMemo", connection);

            command.CommandType = CommandType.StoredProcedure;

            command.Parameters.Add("ID", SqlDbType.Int);

            command.Parameters["ID"].Value = Convert.ToInt32(Request["ID"]);

            command.ExecuteNonQuery();

            connection.Close();

            Response.Redirect("ListPage.aspx");
        }

        #endregion
    }
}

 

▶ SearchPage.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="SearchPage.aspx.cs" Inherits="TestProject.SearchPage" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>데이터베이스 CRUD 작업하기</title>
    </head>
    <body>
        <form id="form" runat="server">
            <div>
                <h3>메모 검색</h3>
                <asp:DropDownList ID="fieldDropDownList" runat="server">
                    <asp:ListItem Value="Title" Selected="True">제목</asp:ListItem>
                    <asp:ListItem Value="[Description]">설명</asp:ListItem>
                </asp:DropDownList>
                <asp:TextBox ID="queryTextBox" runat="server" />
                <asp:Button ID="searchButton" runat="server"
                    Text="검색"
                    OnClick="searchButton_Click" />
                <hr />
                <asp:GridView ID="gridView" runat="server" />
            </div>
        </form>
    </body>
</html>

 

▶ SearchPage.aspx.cs

using System;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Web.UI;

namespace TestProject
{
    /// <summary>
    /// 검색 페이지
    /// </summary>
    public partial class SearchPage : Page
    {
        //////////////////////////////////////////////////////////////////////////////////////////////////// Method
        ////////////////////////////////////////////////////////////////////////////////////////// Protected

        #region 페이지 로드시 처리하기 - Page_Load(sender, e)

        /// <summary>
        /// 페이지 로드시 처리하기
        /// </summary>
        /// <param name="sender">이벤트 발생자</param>
        /// <param name="e">이벤트 인자</param>
        protected void Page_Load(object sender, EventArgs e)
        {
        }

        #endregion
        #region 검색 버튼 클릭시 처리하기 - searchButton_Click(sender, e)

        /// <summary>
        /// 검색 버튼 클릭시 처리하기
        /// </summary>
        /// <param name="sender">이벤트 발생자</param>
        /// <param name="e">이벤트 인자</param>
        protected void searchButton_Click(object sender, EventArgs e)
        {
            string connectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;

            SqlConnection connection = new SqlConnection(connectionString);

            connection.Open();

            SqlCommand command = new SqlCommand("SearchMemo", connection);

            command.CommandType = CommandType.StoredProcedure;

            command.Parameters.AddWithValue("SearchField", this.fieldDropDownList.SelectedValue);
            command.Parameters.AddWithValue("SearchQuery", this.queryTextBox.Text.Replace("--", ""));

            SqlDataAdapter adapter = new SqlDataAdapter(command);

            DataSet dataSet = new DataSet();

            adapter.Fill(dataSet, "Memo");

            this.gridView.DataSource = dataSet.Tables[0].DefaultView;

            this.gridView.DataBind();

            connection.Close();
        }

        #endregion
    }
}
728x90
반응형
그리드형(광고전용)
Posted by icodebroker

댓글을 달아 주세요