ASP.NET 주소록 구현
데이타 베이스 접근시 쉽게 접근하게 하기위하여 클래스파일 생성 내용은 프로퍼티로 get해서
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
/// <summary>
/// UserDB의 요약 설명입니다.
/// </summary>
public class UserDB
{
public UserDB()
{
//
// TODO: 여기에 생성자 논리를 추가합니다.
//
}
public static SqlConnection CreateConnection()
{
SqlConnection con = new SqlConnection();
con.ConnectionString = ConfigurationManager.ConnectionStrings["conStr"].ConnectionString;
con.Open();
return con;
}
public static SqlCommand CreateCommand(string sql)
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = CreateConnection();
cmd.CommandText = sql;
return cmd;
}
}
루트 오른쪽 버튼 ASP.NET 폴더추가 Theme선택하여 공용으로 사용할 스타일 시트 생성
/* address.css */
body, p, div, span, td, table, input, a, textarea
{
font-size:12px;
}
.title { text-align:center; }
.title span { font-size:20px; }
.page
{
text-align:center;
}
#headerPart { height:80px;}
#contentPart
{
width:500px;
min-height:200px;
margin:0px auto;
margin-bottom:20px;
}
#footerPart { height:50px;}
.bar
{
width:500px;
border:0px;
border-top:1px solid gray;
}
.copyright
{
text-align:center;
}
/* 테이블 */
.table
{
border:1px solid black;
width:500px;
border-collapse:collapse;
}
.table td
{
border:1px solid gray;
padding:2px;
}
.leftTD
{
width:120px;
text-align:center;
background-color:#EFEFEF;
font-weight:bold;
}
.table .rightTD
{
width:380px;
padding-left:20px;
}
.btnList
{
margin-top:15px;
}
a
{
text-decoration:none;
color:Black;
}
a:hover
{
color:Blue;
}
List.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="List.aspx.cs" Inherits="List" %>
<%@ Register src="include/Footer.ascx" tagname="Footer" tagprefix="uc2" %>
<%@ Register src="include/Header.ascx" tagname="Header" tagprefix="uc1" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div id="headerPart">
<uc1:Header ID="Header1" runat="server" PageText="주소록 목록" />
</div>
<div id="contentPart">
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataKeyNames="seq" DataSourceID="SqlDataSource1" BackColor="White"
BorderColor="#336666" BorderStyle="Double" BorderWidth="3px" CellPadding="4"
GridLines="Horizontal" Width="500px">
<Columns>
<asp:BoundField DataField="seq" HeaderText="번호" InsertVisible="False"
ReadOnly="True" SortExpression="seq" >
<ItemStyle HorizontalAlign="Center" Width="100px" />
</asp:BoundField>
<asp:HyperLinkField DataNavigateUrlFields="seq"
DataNavigateUrlFormatString="View.aspx?seq={0}" DataTextField="name"
HeaderText="이름">
<ItemStyle HorizontalAlign="Center" Width="100px" />
</asp:HyperLinkField>
<asp:BoundField DataField="address" HeaderText="주소" SortExpression="address" >
<ItemStyle Width="300px" />
</asp:BoundField>
</Columns>
<FooterStyle BackColor="White" ForeColor="#333333" />
<HeaderStyle BackColor="#336666" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#336666" ForeColor="White" HorizontalAlign="Center" />
<RowStyle BackColor="White" ForeColor="#333333" />
<SelectedRowStyle BackColor="#339966" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#F7F7F7" />
<SortedAscendingHeaderStyle BackColor="#487575" />
<SortedDescendingCellStyle BackColor="#E5E5E5" />
<SortedDescendingHeaderStyle BackColor="#275353" />
</asp:GridView>
<div class="btnList">
<asp:Button ID="Button1" runat="server" Text="주소 추가하기" Width="95px"
onclick="Button1_Click" />
</div>
</div>
<div id="footerPart">
<uc2:Footer ID="Footer1" runat="server" />
</div>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:conStr %>"
SelectCommand="SELECT [seq], [name], [address] FROM [tblAddress] ORDER BY seq DESC">
</asp:SqlDataSource>
</form>
</body>
</html>
List.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class List : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
Response.Redirect("Add.aspx");
}
}
View.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="View.aspx.cs" Inherits="View" %>
<%@ Register src="include/Footer.ascx" tagname="Footer" tagprefix="uc2" %>
<%@ Register src="include/Header.ascx" tagname="Header" tagprefix="uc1" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div id="headerPart">
<uc1:Header ID="Header1" runat="server" />
</div>
<div id="contentPart">
<div id="contentPart0">
<table class="table">
<tr>
<td class="leftTD">
번호</td>
<td class="rightTD">
<asp:Label ID="LabelSeq" runat="server" Text="Label"></asp:Label>
</td>
</tr>
<tr>
<td class="leftTD">
이름</td>
<td class="rightTD">
<asp:Label ID="LabelName" runat="server" Text="Label"></asp:Label>
</td>
</tr>
<tr>
<td class="leftTD">
주소</td>
<td class="rightTD">
<asp:Label ID="LabelAddress" runat="server" Text="Label"></asp:Label>
</td>
</tr>
<tr>
<td class="leftTD">
나이</td>
<td class="rightTD">
<asp:Label ID="LabelAge" runat="server" Text="Label"></asp:Label>
</td>
</tr>
<tr>
<td class="leftTD">
성별</td>
<td class="rightTD">
<asp:Label ID="LabelGender" runat="server" Text="Label"></asp:Label>
</td>
</tr>
<tr>
<td class="leftTD">
생일</td>
<td class="rightTD">
<asp:Label ID="LabelBirth" runat="server" Text="Label"></asp:Label>
</td>
</tr>
</table>
<div class="btnList">
<asp:Button ID="Button1" runat="server" Text="목록보기" onclick="Button1_Click" />
<asp:Button ID="Button2" runat="server" Text="수정하기"
ValidationGroup="cancel" onclick="Button2_Click" />
<asp:Button ID="Button3" runat="server" Text="삭제하기" onclick="Button3_Click"
onclientclick="return confirm("정말 삭제하시겠습니까?");" />
</div>
</div>
</div>
<div id="footerPart">
<uc2:Footer ID="Footer1" runat="server" />
</div>
</form>
</body>
</html>
View.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
public partial class View : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//View.aspx?seq=3
string seq = Request.QueryString["seq"];
//SELECT * FROM tblAddress WHERE seq = 3;
SqlCommand cmd = UserDB.CreateCommand("SELECT * FROM tblAddress WHERE seq =" + seq);
SqlDataReader reader = cmd.ExecuteReader();
if (reader.Read())
{
//출력
LabelSeq.Text = reader["seq"].ToString();
LabelName.Text = reader["name"].ToString();
LabelAddress.Text = reader["address"].ToString();
LabelAge.Text = reader["age"].ToString();
LabelGender.Text = (reader["gender"].ToString() == "m") ? "남자" : "여자";
LabelBirth.Text = reader["birth"].ToString().Substring(0,10);
Header1.PageText = string.Format("{0}님의 상세보기", reader["name"].ToString());
reader.Close();
}
else
{
//해당 게시물 없음
string script = "<script type='text/javascript'> alert('해당 게시물이 존재하지 않거나 삭제되었습니다.');history.back();</script>";
this.ClientScript.RegisterClientScriptBlock(this.GetType(), "view", script);
}
}
}
protected void Button1_Click(object sender, EventArgs e)
{
Response.Redirect("List.aspx");
}
protected void Button2_Click(object sender, EventArgs e)
{
//주소에 첨부된 현재 seq
Response.Redirect("Edit.aspx?seq=" + Request.QueryString["seq"]);
}
protected void Button3_Click(object sender, EventArgs e)
{
//Response.Redirect("Del.aspx?seq=" + Request.QueryString["seq"]);
string sql = "DELETE FROM tblAddress WHERE seq=" + Request.QueryString["seq"];
SqlCommand cmd = UserDB.CreateCommand(sql);
int result = cmd.ExecuteNonQuery();//1,0
string script = "";
if (result == 1)
{
script = @"<script type= 'text/javascript'> alert('주소 삭제 완료!!'); location.href='List.aspx';</script>";
}
else
{
script = @"<script type='text/javascript'> alert('주소 삭제 실패!!');<script>";
}
//C#에서 스크립트 실행하는 문.
this.ClientScript.RegisterClientScriptBlock(this.GetType(), "add", script);
}
}
Edit.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Edit.aspx.cs" Inherits="Edit" %>
<%@ Register src="include/Header.ascx" tagname="Header" tagprefix="uc1" %>
<%@ Register src="include/Footer.ascx" tagname="Footer" tagprefix="uc2" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div id="headerPart">
<uc1:Header ID="Header1" runat="server" PageText="주소록 추가" />
</div>
<div id="contentPart">
<table class="table">
<tr>
<td class="leftTD">
이름</td>
<td class="rightTD">
<asp:TextBox ID="TextBoxName" runat="server" Width="80px"></asp:TextBox>
</td>
</tr>
<tr>
<td class="leftTD">
주소</td>
<td class="rightTD">
<asp:TextBox ID="TextBoxAddress" runat="server" Width="90%"></asp:TextBox>
</td>
</tr>
<tr>
<td class="leftTD">
나이</td>
<td class="rightTD">
<asp:DropDownList ID="DropDownListAge" runat="server">
</asp:DropDownList>
</td>
</tr>
<tr>
<td class="leftTD">
성별</td>
<td class="rightTD">
<asp:RadioButtonList ID="RadioButtonListGender" runat="server"
RepeatDirection="Horizontal" RepeatLayout="Flow">
</asp:RadioButtonList>
</td>
</tr>
<tr>
<td class="leftTD">
생일</td>
<td class="rightTD">
<asp:TextBox ID="TextBoxBirth" runat="server" Width="150px"></asp:TextBox>
</td>
</tr>
</table>
<div class="btnList">
<asp:Button ID="Button1" runat="server" Text="수정하기" onclick="Button1_Click1" />
<asp:Button ID="Button2" runat="server" Text="취소하기" ValidationGroup="cancel"
onclick="Button2_Click" />
</div>
</div>
<div id="footerPart">
<uc2:Footer ID="Footer1" runat="server" />
</div>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"
ControlToValidate="TextBoxName" Display="None" ErrorMessage="이름을 입력하세요."
SetFocusOnError="True"></asp:RequiredFieldValidator>
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server"
ControlToValidate="TextBoxAddress" Display="None" ErrorMessage="주소를 입력하세요."
SetFocusOnError="True"></asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server"
ControlToValidate="TextBoxBirth" Display="None" ErrorMessage="생일을 올바르게 입력하세요."
SetFocusOnError="True" ValidationExpression="^\d{4}-\d{1,2}-\d{1,2}$"></asp:RegularExpressionValidator>
<asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server"
ControlToValidate="TextBoxBirth" Display="None" ErrorMessage="생일을 입력하세요."
SetFocusOnError="True"></asp:RequiredFieldValidator>
<asp:ValidationSummary ID="ValidationSummary1" runat="server"
ShowMessageBox="True" ShowSummary="False" />
</form>
</body>
</html>
Edit.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
public partial class Edit : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//나이
for (int i = 15; i <= 35; i++)
{
DropDownListAge.Items.Add(i.ToString());
}
//성별
RadioButtonListGender.Items.Add(new ListItem("남자", "m"));
RadioButtonListGender.Items.Add(new ListItem("여자", "f"));
//Edit.aspx?seq=3
string seq = Request.QueryString["seq"];
//SELECT * FROM tblAddress WHERE seq = 3;
SqlCommand cmd = UserDB.CreateCommand("SELECT * FROM tblAddress WHERE seq =" + seq);
SqlDataReader reader = cmd.ExecuteReader();
if (reader.Read())
{
//출력
TextBoxName.Text = reader["name"].ToString();
TextBoxAddress.Text = reader["address"].ToString();
DropDownListAge.SelectedValue = reader["age"].ToString();
RadioButtonListGender.SelectedIndex = (reader["gender"] == "m") ? 0 : 1;
TextBoxBirth.Text = reader["birth"].ToString().Substring(0, 10);
Header1.PageText = string.Format("{0}님의 정보 수정하기", reader["name"].ToString());
reader.Close();
}
else
{
//해당 게시물 없음
string script = "<script type='text/javascript'> alert('해당 게시물이 존재하지 않거나 삭제되었습니다.');history.back();</script>";
this.ClientScript.RegisterClientScriptBlock(this.GetType(), "view", script);
}
}
}
protected void Button1_Click1(object sender, EventArgs e)
{
//수정하기 -> Update
string sql = string.Format("UPDATE tblAddress SET name='{0}', address='{1}', age={2}, gender='{3}', birth='{4}' WHERE seq={5}", TextBoxName.Text.Trim(), TextBoxAddress.Text.Trim(), DropDownListAge.SelectedItem.Value, RadioButtonListGender.SelectedItem.Value, TextBoxBirth.Text.Trim(), Request.QueryString["seq"]);
SqlCommand cmd = UserDB.CreateCommand(sql);
int result = cmd.ExecuteNonQuery();//1,0
string script = "";
if (result == 1)
{
script = @"<script type= 'text/javascript'> alert('주소 수정 완료!!'); location.href='View.aspx?seq=" + Request.QueryString["seq"] + "';</script>";
}
else
{
script = @"<script type='text/javascript'> alert('주소 수정 실패!!');<script>";
}
//C#에서 스크립트 실행하는 문.
this.ClientScript.RegisterClientScriptBlock(this.GetType(), "add", script);
}
protected void Button2_Click(object sender, EventArgs e)
{
Response.Redirect("View.aspx?seq=" + Request.QueryString["seq"]);
}
}
Add.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Add.aspx.cs" Inherits="Add" %>
<%@ Register src="include/Footer.ascx" tagname="Footer" tagprefix="uc2" %>
<%@ Register src="include/Header.ascx" tagname="Header" tagprefix="uc1" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<style type="text/css">
.style1
{
width: 100%;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div id="headerPart">
<uc1:Header ID="Header1" runat="server" PageText="주소록 추가" />
</div>
<div id="contentPart">
<table class="table">
<tr>
<td class="leftTD">
이름</td>
<td class="rightTD">
<asp:TextBox ID="TextBoxName" runat="server" Width="80px"></asp:TextBox>
</td>
</tr>
<tr>
<td class="leftTD">
주소</td>
<td class="rightTD">
<asp:TextBox ID="TextBoxAddress" runat="server" Width="90%"></asp:TextBox>
</td>
</tr>
<tr>
<td class="leftTD">
나이</td>
<td class="rightTD">
<asp:DropDownList ID="DropDownListAge" runat="server">
</asp:DropDownList>
</td>
</tr>
<tr>
<td class="leftTD">
성별</td>
<td class="rightTD">
<asp:RadioButtonList ID="RadioButtonListGender" runat="server"
RepeatDirection="Horizontal" RepeatLayout="Flow">
</asp:RadioButtonList>
</td>
</tr>
<tr>
<td class="leftTD">
생일</td>
<td class="rightTD">
<asp:TextBox ID="TextBoxBirth" runat="server" Width="150px"></asp:TextBox>
</td>
</tr>
</table>
<div class="btnList">
<asp:Button ID="Button1" runat="server" Text="추가하기" onclick="Button1_Click1" />
<asp:Button ID="Button2" runat="server" Text="취소하기" ValidationGroup="cancel"
onclick="Button2_Click1" />
</div>
</div>
<div id="footerPart">
<uc2:Footer ID="Footer1" runat="server" />
</div>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"
ControlToValidate="TextBoxName" Display="None" ErrorMessage="이름을 입력하세요."
SetFocusOnError="True"></asp:RequiredFieldValidator>
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server"
ControlToValidate="TextBoxAddress" Display="None" ErrorMessage="주소를 입력하세요."
SetFocusOnError="True"></asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server"
ControlToValidate="TextBoxBirth" Display="None" ErrorMessage="생일을 올바르게 입력하세요."
SetFocusOnError="True" ValidationExpression="^\d{4}-\d{1,2}-\d{1,2}$"></asp:RegularExpressionValidator>
<asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server"
ControlToValidate="TextBoxBirth" Display="None" ErrorMessage="생일을 입력하세요."
SetFocusOnError="True"></asp:RequiredFieldValidator>
<asp:ValidationSummary ID="ValidationSummary1" runat="server"
ShowMessageBox="True" ShowSummary="False" />
</form>
</body>
</html>
Add.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
public partial class Add : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//컨트롤 초기화
if (!IsPostBack)
{
//나이
for (int i = 15; i <= 35; i++)
{
DropDownListAge.Items.Add(i.ToString());
}
//선택값
DropDownListAge.SelectedIndex = 10;
//성별
RadioButtonListGender.Items.Add(new ListItem("남자", "m"));
RadioButtonListGender.Items.Add(new ListItem("여자", "f"));
RadioButtonListGender.SelectedIndex = 0;
}
}
protected void Button1_Click1(object sender, EventArgs e)
{
//추가하기(DB)
//insert문
string sql = string.Format("insert into tblAddress (name, address, age, gender, birth) values ('{0}', '{1}', {2}, '{3}', '{4}');", TextBoxName.Text.Trim(), TextBoxAddress.Text.Trim(), DropDownListAge.SelectedItem.Value, RadioButtonListGender.SelectedItem.Value, TextBoxBirth.Text.Trim());
//실행
SqlCommand cmd = UserDB.CreateCommand(sql);
int result = cmd.ExecuteNonQuery();//1,0
string script = "";
if (result==1)
{
script = @"<script type= 'text/javascript'> alert('주소 추가 완료!!'); location.href='List.aspx';</script>";
}
else
{
script = @"<script type='text/javascript'> alert('주소 추가 실패!!');<script>";
}
//C#에서 스크립트 실행하는 문.
this.ClientScript.RegisterClientScriptBlock(this.GetType(), "add", script);
//Response.Write(sql);
//Response.End();
}
protected void Button2_Click1(object sender, EventArgs e)
{
Response.Redirect("List.aspx");
}
}
web.config
<?xml version="1.0"?>
<!--
ASP.NET 응용 프로그램을 구성하는 방법에 대한 자세한 내용을 보려면
http://go.microsoft.com/fwlink/?LinkId=169433 을 방문하십시오.
-->
<configuration>
<connectionStrings>
<add name="conStr" connectionString="Data Source=localhost;Initial Catalog=ASPNET;Persist Security Info=True;User ID=sa;Password=zangna1"
providerName="System.Data.SqlClient" />
</connectionStrings>
<system.web>
<compilation debug="false" targetFramework="4.0" />
<pages theme="basic" />
</system.web>
</configuration>