본문 바로가기

   
Programming/ASP.NET(4.0)

ASP.NET 댓글 게시판 예제

반응형

ASP.NET 댓글 게시판 예제



web.config

<?xml version="1.0"?>

 

<!--

  ASP.NET 응용 프로그램을 구성하는 방법에 대한 자세한 내용을 보려면

  http://go.microsoft.com/fwlink/?LinkId=169433 을 방문하십시오.

  -->

 

<configuration>

       <connectionStrings>

             <add name="conStr" connectionString="server=localhost;database=ASPNET;uid=sa;pwd=zangna1" providerName="System.Data.SqlClient" />                    

       </connectionStrings>

 

    <system.web>

        <compilation debug="false" targetFramework="4.0" />

             <httpRuntime requestValidationMode="2.0" />

             <pages theme="basic" />

    </system.web>

 

</configuration>

 

 

Add.aspx

<%@ Page Title="" Language="C#" MasterPageFile="~/Board.master" AutoEventWireup="true" CodeFile="Add.aspx.cs" Inherits="Add" ValidateRequest="false" %>

 

<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">

       </asp:Content>

 

<asp:Content ID="Content2" runat="server"

       contentplaceholderid="ContentPlaceHolder1">

       <table class="table" style="width:600px;">

             <tr>

                    <td align="center" bgcolor="Silver" width="150">

                           이름</td>

                    <td width="450">

                           &nbsp;<asp:TextBox ID="TextBoxName" runat="server" CssClass="txt" Width="100px"></asp:TextBox>

                           &nbsp;</td>

             </tr>

             <tr>

                    <td align="center" bgcolor="Silver" width="150">

                           이메일</td>

                    <td width="450">

                           &nbsp;<asp:TextBox ID="TextBoxEmail" runat="server" CssClass="txt" Width="250px"></asp:TextBox>

                           &nbsp;</td>

             </tr>

             <tr>

                    <td align="center" bgcolor="Silver" width="150">

                           제목</td>

                    <td width="450">

                           &nbsp;<asp:TextBox ID="TextBoxSubject" runat="server" CssClass="txt" Width="95%"></asp:TextBox>

                           &nbsp;</td>

             </tr>

             <tr>

                    <td align="center" bgcolor="Silver" width="150">

                           내용</td>

                    <td width="450">

                           &nbsp;<asp:TextBox ID="TextBoxContent" runat="server" CssClass="txt" Height="150px"

                                 TextMode="MultiLine" Width="95%"></asp:TextBox>

                           &nbsp;</td>

             </tr>

             <tr>

                    <td align="center" bgcolor="Silver" width="150">

                           태그적용</td>

                    <td width="450">

                           &nbsp;<asp:CheckBox ID="CheckBoxTag" runat="server" Text="HTML 태그 적용함" />

                           &nbsp;</td>

             </tr>

             <tr>

                    <td align="center" bgcolor="Silver" width="150">

                           암호</td>

                    <td width="450">

                           &nbsp;<asp:TextBox ID="TextBoxPwd" runat="server" CssClass="txt" TextMode="Password"

                                 Width="100px"></asp:TextBox>

                           &nbsp;</td>

             </tr>

       </table>

       <div style="text-align:center;margin:10px;">

             <asp:ImageButton ID="ImageButton1" runat="server" ImageUrl="~/images/list.gif"

                    onclick="ImageButton1_Click" ValidationGroup="list" />

&nbsp;<asp:ImageButton ID="ImageButton2" runat="server" ImageUrl="~/images/write.gif"

                    onclick="ImageButton2_Click" />

             <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"

                    ControlToValidate="TextBoxName" Display="None" ErrorMessage="이름을 입력하세요."

                    SetFocusOnError="True"></asp:RequiredFieldValidator>

             <asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server"

                    ControlToValidate="TextBoxSubject" Display="None" ErrorMessage="제목을 입력하세요."

                    SetFocusOnError="True"></asp:RequiredFieldValidator>

             <asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server"

                    ControlToValidate="TextBoxContent" Display="None" ErrorMessage="내용을 입력하세요."

                    SetFocusOnError="True"></asp:RequiredFieldValidator>

             <asp:RequiredFieldValidator ID="RequiredFieldValidator4" runat="server"

                    ControlToValidate="TextBoxPwd" Display="None" ErrorMessage="암호를 입력하세요."

                    SetFocusOnError="True"></asp:RequiredFieldValidator>

             <asp:ValidationSummary ID="ValidationSummary1" runat="server"

                    ShowMessageBox="True" ShowSummary="False" />

       </div>

</asp:Content>

 

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)

    {

 

    }

       protected void ImageButton1_Click(object sender, ImageClickEventArgs e)

       {

             //List

             Response.Redirect("List.aspx");

       }

       protected void ImageButton2_Click(object sender, ImageClickEventArgs e)

       {

             //Write

             SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["conStr"].ConnectionString);

 

             SqlCommand cmd = new SqlCommand();

             cmd.Connection = con;

             cmd.CommandText = "insert into Board (name, email, subject, content, tag, pwd, userIP, thread, depth) values (@name, @email, @subject, @content, @tag, @pwd, @userIP, @thread, @depth)";

 

             //매개변수

             cmd.Parameters.Add("@name", SqlDbType.NVarChar, 20);

             cmd.Parameters.Add("@email", SqlDbType.VarChar, 50);

             cmd.Parameters.Add("@subject", SqlDbType.NVarChar, 100);

             cmd.Parameters.Add("@content", SqlDbType.NVarChar, 3000);

             cmd.Parameters.Add("@tag", SqlDbType.Char, 1);

             cmd.Parameters.Add("@pwd", SqlDbType.VarChar, 20);

             cmd.Parameters.Add("@userIP", SqlDbType.VarChar, 15);

             cmd.Parameters.Add("@thread", SqlDbType.Int);

             cmd.Parameters.Add("@depth", SqlDbType.Int);

 

             //

             cmd.Parameters["@name"].Value = TextBoxName.Text;

             cmd.Parameters["@email"].Value = TextBoxEmail.Text;

             cmd.Parameters["@subject"].Value = TextBoxSubject.Text;

             cmd.Parameters["@content"].Value = TextBoxContent.Text;

             cmd.Parameters["@tag"].Value = CheckBoxTag.Checked ? "y" : "n";

             cmd.Parameters["@pwd"].Value = TextBoxPwd.Text;

             cmd.Parameters["@userIP"].Value = Request.UserHostAddress;

 

 

             con.Open();

 

             //새글? 답변글?

             SqlCommand cmd2 = new SqlCommand();

             cmd2.Connection = con;

 

             if (Request["reply"] != "y")

             {

                    //새글

                    //a. 현재 테이블에 존재하는 모든 thread값 중에서 가장 큰thread + 1000을 한 값을 새글의 thread로 대입

                    cmd2.CommandText = "select isnull(max(thread),0) + 1000 from Board";

                    cmd.Parameters["@thread"].Value = (int)cmd2.ExecuteScalar();

 

                    //b. 새글의 depth 0을 대입

                    cmd.Parameters["@depth"].Value = 0;

             }

             else

             {

                    //답변글

                    //부모글의 thread : Add.aspx?thread=1000&depth=0

                    int parentThread = int.Parse(Request.QueryString["thread"]);

                    int parentDepth = int.Parse(Request.QueryString["depth"]);

 

                    //이전 새글의 thread

                    int prevThread = (int)Math.Floor((parentThread - 1) / 1000D) * 1000;

 

                    cmd2.CommandText = string.Format(@"UPDATE Board SET thread = thread - 1

                                                                            WHERE  thread < {0}

                                                                           AND thread > {1}", parentThread, prevThread);

                    cmd2.ExecuteNonQuery();

 

 

                    //b. 현재 답변글은 thread값을 부모글의 thread -1 대입

                    cmd.Parameters["@thread"].Value = parentThread - 1;

 

                    //c. 현재 답변글은 depth값을 부모글의 depth + 1 대입

                    cmd.Parameters["@depth"].Value = parentDepth + 1;

             }

 

 

             cmd.ExecuteNonQuery();

             con.Close();

 

             string script = @"<script type='text/javascript'>

                                              alert('글쓰기 완료!!');

                                              location.href = 'List.aspx';

                                          </script>";

             this.ClientScript.RegisterClientScriptBlock(this.GetType(), "add", script);

       }

}

 




Del.aspx

<%@ Page Title="" Language="C#" MasterPageFile="~/Board.master" AutoEventWireup="true" CodeFile="Del.aspx.cs" Inherits="Del" %>

 

<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">

</asp:Content>

<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">

       <table class="table" style="width:300px;" align="center">

             <tr>

                    <td align="center" bgcolor="Silver" width="150">

                           암호</td>

                    <td width="150">

                           &nbsp;<asp:TextBox ID="TextBoxPwd" runat="server" CssClass="txt" Width="100px" TextMode="Password"></asp:TextBox>

                           &nbsp;</td>

             </tr>

       </table>

       <div style="text-align:center;margin:10px;">

             <asp:ImageButton ID="ImageButton1" runat="server"

                    ImageUrl="~/images/back.gif" />

&nbsp;<asp:ImageButton ID="ImageButton2" runat="server"

                    ImageUrl="~/images/delete.gif" onclick="ImageButton2_Click" />

&nbsp;</div>

</asp:Content>

 

 

 


Del.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 Del : System.Web.UI.Page

{

    protected void Page_Load(object sender, EventArgs e)

    {

 

    }

       protected void ImageButton2_Click(object sender, ImageClickEventArgs e)

       {

             //삭제하기

             //1. 암호가 일치?

             //2. 삭제 or 취소

             SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["conStr"].ConnectionString);

 

             SqlCommand cmd = new SqlCommand();

             cmd.Connection = con;

             cmd.CommandText = "select count(*) from Board where seq=@seq and pwd=@pwd";

 

             cmd.Parameters.Add("@seq", SqlDbType.Int);

             cmd.Parameters.Add("@pwd", SqlDbType.VarChar, 20);

 

             cmd.Parameters["@seq"].Value = Request.QueryString["seq"];

             cmd.Parameters["@pwd"].Value = TextBoxPwd.Text;

 

             con.Open();

             int result = (int)cmd.ExecuteScalar();

 

 

             string script = "";

 

             if (result == 1)

             {

                    //암호가 일치하기 때문에.. 게시물 Delete

                    cmd.CommandText = @"delete from Board

                                              where seq=@seq";

 

                    cmd.ExecuteNonQuery();//delete

 

                    script = @"<script type='text/javascript'>

                                        alert('삭제 완료!!');

                                        location.href='List.aspx';

                                    </script>";

             }

             else

             {

                    script = @"<script type='text/javascript'>

                                        alert('암호가 일치하지 않습니다!!');

                                    </script>";

             }

 

             con.Close();

 

             this.ClientScript.RegisterClientScriptBlock(this.GetType(), "edit", script);

       }

}

 



Edit.aspx

<%@ Page Title="" Language="C#" MasterPageFile="~/Board.master" AutoEventWireup="true" CodeFile="Edit.aspx.cs" Inherits="Edit" ValidateRequest="false" %>

 

<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">

</asp:Content>

<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">

       <table class="table" style="width:600px;">

             <tr>

                    <td align="center" bgcolor="Silver" width="150">

                           이름</td>

                    <td width="450">

                           &nbsp;<asp:TextBox ID="TextBoxName" runat="server" CssClass="txt" Width="100px"></asp:TextBox>

                           &nbsp;</td>

             </tr>

             <tr>

                    <td align="center" bgcolor="Silver" width="150">

                           이메일</td>

                    <td width="450">

                           &nbsp;<asp:TextBox ID="TextBoxEmail" runat="server" CssClass="txt" Width="250px"></asp:TextBox>

                           &nbsp;</td>

             </tr>

             <tr>

                    <td align="center" bgcolor="Silver" width="150">

                           제목</td>

                    <td width="450">

                           &nbsp;<asp:TextBox ID="TextBoxSubject" runat="server" CssClass="txt" Width="95%"></asp:TextBox>

                           &nbsp;</td>

             </tr>

             <tr>

                    <td align="center" bgcolor="Silver" width="150">

                           내용</td>

                    <td width="450">

                           &nbsp;<asp:TextBox ID="TextBoxContent" runat="server" CssClass="txt" Height="150px"

                                 TextMode="MultiLine" Width="95%"></asp:TextBox>

                           &nbsp;</td>

             </tr>

             <tr>

                    <td align="center" bgcolor="Silver" width="150">

                           태그적용</td>

                    <td width="450">

                           &nbsp;<asp:CheckBox ID="CheckBoxTag" runat="server" Text="HTML 태그 적용함" />

                           &nbsp;</td>

             </tr>

             <tr>

                    <td align="center" bgcolor="Silver" width="150">

                           암호</td>

                    <td width="450">

                           &nbsp;<asp:TextBox ID="TextBoxPwd" runat="server" CssClass="txt" TextMode="Password"

                                 Width="100px"></asp:TextBox>

                           &nbsp;</td>

             </tr>

       </table>

       <div style="text-align:center;margin:10px;">

             <asp:ImageButton ID="ImageButton1" runat="server" ImageUrl="~/images/back.gif"

                    onclick="ImageButton1_Click" ValidationGroup="list" Width="39px" />

&nbsp;<asp:ImageButton ID="ImageButton2" runat="server" ImageUrl="~/images/modify.gif"

                    onclick="ImageButton2_Click" />

             <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"

                    ControlToValidate="TextBoxName" Display="None" ErrorMessage="이름을 입력하세요."

                    SetFocusOnError="True"></asp:RequiredFieldValidator>

             <asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server"

                    ControlToValidate="TextBoxSubject" Display="None" ErrorMessage="제목을 입력하세요."

                    SetFocusOnError="True"></asp:RequiredFieldValidator>

             <asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server"

                    ControlToValidate="TextBoxContent" Display="None" ErrorMessage="내용을 입력하세요."

                    SetFocusOnError="True"></asp:RequiredFieldValidator>

             <asp:RequiredFieldValidator ID="RequiredFieldValidator4" runat="server"

                    ControlToValidate="TextBoxPwd" Display="None" ErrorMessage="암호를 입력하세요."

                    SetFocusOnError="True"></asp:RequiredFieldValidator>

             <asp:ValidationSummary ID="ValidationSummary1" runat="server"

                    ShowMessageBox="True" ShowSummary="False" />

       </div>

</asp:Content>

 

 

 


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;

using System.Configuration;

 

public partial class Edit : System.Web.UI.Page

{

    protected void Page_Load(object sender, EventArgs e)

    {

             if (!IsPostBack)

             {

                    SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["conStr"].ConnectionString);

 

                    SqlCommand cmd = new SqlCommand();

                    cmd.Connection = con;

                    cmd.CommandText = "select * from Board where seq=@seq";

 

                    cmd.Parameters.Add("@seq", SqlDbType.Int);

                    cmd.Parameters["@seq"].Value = Request.QueryString["seq"];

 

                    con.Open();

 

                    SqlDataReader reader = cmd.ExecuteReader();

 

                    if (reader.Read())

                    {

                           //출력

                           TextBoxName.Text = reader["name"].ToString();

                           TextBoxEmail.Text = reader["email"].ToString();

                           TextBoxSubject.Text = reader["subject"].ToString();

                           //글내용

                           TextBoxContent.Text = reader["content"].ToString();

                           CheckBoxTag.Checked = reader["tag"].ToString() == "y" ? true : false;

                    }

 

                    reader.Close();

                    con.Close();

             }

    }

       protected void ImageButton1_Click(object sender, ImageClickEventArgs e)

       {

 

       }

       protected void ImageButton2_Click(object sender, ImageClickEventArgs e)

       {

             //수정하기

             //1. 암호가 일치?

             //2. 수정 or 취소

             SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["conStr"].ConnectionString);

 

             SqlCommand cmd = new SqlCommand();

             cmd.Connection = con;

             cmd.CommandText = "select count(*) from Board where seq=@seq and pwd=@pwd";

 

             cmd.Parameters.Add("@seq", SqlDbType.Int);

             cmd.Parameters.Add("@pwd", SqlDbType.VarChar, 20);

 

             cmd.Parameters["@seq"].Value = Request.QueryString["seq"];

             cmd.Parameters["@pwd"].Value = TextBoxPwd.Text;

 

             con.Open();

             int result = (int)cmd.ExecuteScalar();

            

 

             string script = "";

 

             if (result == 1)

             {

                    //암호가 일치하기 때문에.. 게시물 Update

                    cmd.CommandText = @"update Board set

                                                     name=@name,

                                                     email=@email,

                                                     subject=@subject,

                                                     content=@content,

                                                     tag=@tag,

                                                     userIP=@userIP,

                                                     regDate=getdate()

                                              where seq=@seq";

 

                    //매개변수

                    cmd.Parameters.Add("@name", SqlDbType.NVarChar, 20);

                    cmd.Parameters.Add("@email", SqlDbType.VarChar, 50);

                    cmd.Parameters.Add("@subject", SqlDbType.NVarChar, 100);

                    cmd.Parameters.Add("@content", SqlDbType.NVarChar, 3000);

                    cmd.Parameters.Add("@tag", SqlDbType.Char, 1);

                    cmd.Parameters.Add("@userIP", SqlDbType.VarChar, 15);

 

                    //

                    cmd.Parameters["@name"].Value = TextBoxName.Text;

                    cmd.Parameters["@email"].Value = TextBoxEmail.Text;

                    cmd.Parameters["@subject"].Value = TextBoxSubject.Text;

                    cmd.Parameters["@content"].Value = TextBoxContent.Text;

                    cmd.Parameters["@tag"].Value = CheckBoxTag.Checked ? "y" : "n";

                    cmd.Parameters["@userIP"].Value = Request.UserHostAddress;

 

                    cmd.ExecuteNonQuery();//update

 

                    script = @"<script type='text/javascript'>

                                        alert('수정 완료!!');

                                        location.href='List.aspx';

                                    </script>";

             }

             else

             {

                    script = @"<script type='text/javascript'>

                                        alert('암호가 일치하지 않습니다!!');

                                    </script>";

             }

 

             con.Close();

 

             this.ClientScript.RegisterClientScriptBlock(this.GetType(), "edit", script);

       }

}

 



List.aspx

<%@ Page Title="" Language="C#" MasterPageFile="~/Board.master" AutoEventWireup="true" CodeFile="List.aspx.cs" Inherits="List" Trace="true" %>

 

<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">

</asp:Content>

<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">

       <asp:GridView ID="GridView1" runat="server" AllowPaging="True"

             AutoGenerateColumns="False" CssClass="table" DataKeyNames="seq"

             DataSourceID="SqlDataSource1" onrowdatabound="GridView1_RowDataBound"

             Width="600px">

             <Columns>

                    <asp:BoundField DataField="seq" HeaderText="번호" InsertVisible="False"

                           ReadOnly="True" SortExpression="seq">

                    <ItemStyle HorizontalAlign="Center" Width="50px" />

                    </asp:BoundField>

                    <asp:HyperLinkField DataNavigateUrlFields="seq"

                           DataNavigateUrlFormatString="View.aspx?seq={0}" DataTextField="subject"

                           HeaderText="제목">

                    <ItemStyle Width="340px" />

                    </asp:HyperLinkField>

                    <asp:BoundField DataField="name" HeaderText="이름" SortExpression="name">

                    <ItemStyle HorizontalAlign="Center" Width="80px" />

                    </asp:BoundField>

                    <asp:BoundField DataField="regDate" DataFormatString="{0:yyyy-MM-dd}"

                           HeaderText="날짜" SortExpression="regDate">

                    <ItemStyle HorizontalAlign="Center" Width="80px" />

                    </asp:BoundField>

                    <asp:BoundField DataField="readCount" HeaderText="읽음"

                           SortExpression="readCount">

                    <ItemStyle HorizontalAlign="Center" Width="50px" />

                    </asp:BoundField>

             </Columns>

             <HeaderStyle BorderStyle="Solid" BorderWidth="1px" />

       </asp:GridView>

       <asp:SqlDataSource ID="SqlDataSource1" runat="server"

             ConnectionString="<%$ ConnectionStrings:conStr %>"

             SelectCommand="SELECT [seq], [name], [subject], [readCount], [regDate], [email], [depth] FROM [Board] ORDER BY [thread] DESC">

       </asp:SqlDataSource>

       <div style="text-align:center;margin:10px;">

             &nbsp;<asp:ImageButton ID="ImageButton1" runat="server"

                    ImageUrl="~/images/write.gif" onclick="ImageButton1_Click" />

       </div>

</asp:Content>

 

 

 


List.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;

 

public partial class List : System.Web.UI.Page

{

    protected void Page_Load(object sender, EventArgs e)

    {

             if (!IsPostBack)

             {

                    //조회수 증가용 쿠키 할당

                    Response.Cookies["read"].Value = "n";

             }

    }

       protected void ImageButton1_Click(object sender, ImageClickEventArgs e)

       {

             //글쓰기

             Response.Redirect("Add.aspx");

       }

       protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)

       {

             if (e.Row.RowType == DataControlRowType.DataRow)

             {

                    //1. 제목이 길면.. 자르기

                    //e.Row <- 한행(GridViewRow) x 5

                    HyperLink subject = e.Row.Cells[1].Controls[0] as HyperLink;

 

                    if (subject.Text.Length > 20)

                    {

                           subject.Text = subject.Text.Substring(0, 20) + "...";

                    }

 

 

                    //2. 글쓴지 일정시간이내면.. new.gif 표시

                    // 30분이내

                    //Response.Write(e.Row.Cells[3].Text + "<br />");

 

                    //현재 바인딩되거나 바인딩된 데이터에 접근하는 방법

                    //A. 출력된 결과값에 접근하는 방법(Cells을 사용)

                    //Response.Write(e.Row.Cells[2].Text);

 

                    //B. (출력과 상관없이)바인딩되는 원본에 접근하는 방법

                    // 조건 : 데이터원본에는 있어야함(select의 대상)

                    //데이터원본(seq, subject, name, regDate, readCount, email)

                    DataRowView row = e.Row.DataItem as DataRowView;

                    //Response.Write(row["email"].ToString());

                    //Response.Write(row["regDate"].ToString());

                    DateTime regDate = (DateTime)row["regDate"];

 

                    TimeSpan gap = DateTime.Now - regDate;

 

                    if (gap.TotalMinutes <= 30)

                    {

                           //30이내에 쓴글

                           //e.Row.Cells[1]

                           LiteralControl img = new LiteralControl("<img src='images/new.gif' alt='새글' style='margin-left:5px;' />");

                           e.Row.Cells[1].Controls.Add(img);

                           //e.Row.Cells[1].Controls.AddAt(0, img);

                    }

 

 

                    //3. 답변글은 제목앞에 re.gif 붙이기

                    int depth = (int)row["depth"];

 

                    if (depth > 0)

                    {

                           LiteralControl img = new LiteralControl("<img src='images/re.gif' alt='' style='margin-right:5px;margin-left:" + (depth * 15) + "px' />");

                           e.Row.Cells[1].Controls.AddAt(0,img);

 

                           e.Row.Cells[0].Text = "";

 

                    }

             }

       }

}

 



View.aspx

<%@ Page Title="" Language="C#" MasterPageFile="~/Board.master" AutoEventWireup="true" CodeFile="View.aspx.cs" Inherits="View" %>

 

<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">

</asp:Content>

<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">

       <table class="table" style="width:600px;">

             <tr>

                    <td align="center" bgcolor="Silver" width="150">

                           이름</td>

                    <td width="450">

                           &nbsp;<asp:Label ID="LabelName" runat="server"></asp:Label>

                           &nbsp;</td>

             </tr>

             <tr>

                    <td align="center" bgcolor="Silver" width="150">

                           이메일</td>

                    <td width="450">

                           &nbsp;<asp:Label ID="LabelEmail" runat="server"></asp:Label>

                           &nbsp;</td>

             </tr>

             <tr>

                    <td align="center" bgcolor="Silver" width="150">

                           제목</td>

                    <td width="450">

                           &nbsp;<asp:Label ID="LabelSubject" runat="server"></asp:Label>

                           &nbsp;</td>

             </tr>

             <tr>

                    <td align="center" bgcolor="Silver" width="150">

                           내용</td>

                    <td width="450" style="padding:10px;">

                           <asp:Label ID="LabelContent" runat="server"></asp:Label>

                    </td>

             </tr>

             <tr>

                    <td align="center" bgcolor="Silver" width="150">

                           번호</td>

                    <td width="450">

                           &nbsp;<asp:Label ID="LabelSeq" runat="server"></asp:Label>

                           &nbsp;</td>

             </tr>

             <tr>

                    <td align="center" bgcolor="Silver" width="150">

                           읽음</td>

                    <td width="450">

                           &nbsp;<asp:Label ID="LabelReadCount" runat="server"></asp:Label>

                           &nbsp;</td>

             </tr>

             <tr>

                    <td align="center" bgcolor="Silver" width="150">

                           날짜</td>

                    <td width="450">

                           &nbsp;<asp:Label ID="LabelRegDate" runat="server"></asp:Label>

                           &nbsp;</td>

             </tr>

       </table>

       <div style="text-align:center;margin:10px;">

             <asp:ImageButton ID="ImageButton1" runat="server" ImageUrl="~/images/list.gif"

                    onclick="ImageButton1_Click" ValidationGroup="list" />

&nbsp;<asp:ImageButton ID="ImageButton3" runat="server" ImageUrl="~/images/modify.gif"

                    onclick="ImageButton3_Click" />

&nbsp;<asp:ImageButton ID="ImageButton4" runat="server" ImageUrl="~/images/delete.gif"

                    onclick="ImageButton4_Click" />

       &nbsp;<asp:ImageButton ID="ImageButton5" runat="server"

                    ImageUrl="~/images/reply.gif" onclick="ImageButton5_Click" />

       </div>

</asp:Content>

 

 

 

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)

             {

                    //seq의 상세보기

                    SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["conStr"].ConnectionString);

 

                    SqlCommand cmd = new SqlCommand();

                    cmd.Connection = con;

                    cmd.CommandText = "update Board set readCount = readCount + 1 where seq=@seq;";

 

                    cmd.Parameters.Add("@seq", SqlDbType.Int);

                    cmd.Parameters["@seq"].Value = Request.QueryString["seq"];

 

                    con.Open();

 

                    //쿠키 확인 작업

                    if (Request.Cookies["read"] == null || Request.Cookies["read"].Value == "n")

                    {

                           cmd.ExecuteNonQuery();//조회수 증가

                           Response.Cookies["read"].Value = "y";

                    }

 

                    cmd.CommandText = "select * from Board where seq=@seq";

                   

                    SqlDataReader reader = cmd.ExecuteReader();

                    if (reader.Read())

                    {

                           //출력

                           LabelName.Text = string.Format("{0} [{1}]", reader["name"].ToString(), reader["userIP"].ToString());

                           LabelEmail.Text = reader["email"].ToString();

                           LabelSubject.Text = reader["subject"].ToString();

 

                           //글내용

                           string content = reader["content"].ToString();

 

                           //태그적용 안함 처리 ( < -> &lt;)

                           if (reader["tag"].ToString() == "n")

                           {

                                 content = Server.HtmlEncode(content);

                           }

 

                           //<script> 무조건 적용안함

                           content = content.Replace("<script", "&lt;script").Replace("</script>", "&lt/script>");

 

                           //엔터값처리  -> <br />

                           content = content.Replace("\r\n", "<br />");

 

                           LabelContent.Text = content;

 

 

                           LabelSeq.Text = reader["seq"].ToString();

                           LabelReadCount.Text = reader["readCount"].ToString();

                           LabelRegDate.Text = reader["regDate"].ToString();

 

 

                           //포스트백이 일어날때만 상태유지.. ViewState

                           ViewState["thread"] = reader["thread"].ToString();

                           ViewState["depth"] = reader["depth"].ToString();

                    }

 

                    reader.Close();

                    con.Close();

             }

    }

       protected void ImageButton1_Click(object sender, ImageClickEventArgs e)

       {

             //List

             Response.Redirect("List.aspx");

       }

       protected void ImageButton3_Click(object sender, ImageClickEventArgs e)

       {

             //수정 Edit.aspx?seq=5

             Response.Redirect("Edit.aspx?seq=" + Request.QueryString["seq"]);

       }

       protected void ImageButton4_Click(object sender, ImageClickEventArgs e)

       {

             //삭제 Del.aspx?seq=5

             Response.Redirect("Del.aspx?seq=" + Request.QueryString["seq"]);

       }

       protected void ImageButton5_Click(object sender, ImageClickEventArgs e)

       {

             //답변하기

             // - 부모글의 thread depth을 알아야.. 로직 처리

 

             //Add.aspx?thread=1000&depth=0

             Response.Redirect(string.Format("Add.aspx?reply=y&thread={0}&depth={1}", ViewState["thread"].ToString(), ViewState["depth"].ToString()));

 

 

       }

}

 

반응형