본문 바로가기

   
Programming/ASP.NET(4.0)

ASP.NET 데이터 바인딩, img, path, 유저컨트롤

반응형

ASP.NET Requst, Response, Application, Session, Server

데이터 바인딩(Data Binding)

- 데이터소스(원본) + 컨트롤(출력)

- 데이터 바인딩이란 데이터 소스를 컨트롤 통해서 자동으로 출력해주는 기술

- 데이터소스 : 변수, 배열, 컬렉션, DataReader, DataTable, DataView, Procedure..

- 컨트롤 : 1개 이상의 내부 항목을 가지는 컨트롤..

- 개발자가 편함..(생산성, 유지보수..)



데이터 바인딩의 종류

1. 단일값 바인딩

-> 데이터소스가 단일값일때 컨트롤 통해서 출력

2. 다중값 바인딩(*****)

-> 데이터소스가 다중값일때 컨트롤 통해서 출력



데이터 바인딩 표현식

- <%# 데이터소스 %>

- 현재 표현식 위치에.. 표현한 데이터소스 가져와 대입




<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Ex32_DataBind.aspx.cs" Inherits="Ex32_DataBind" %>

 

<!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>

   

       <h2>

                    Ex32_DataBind.aspx</h2>

             <br />

             <h2>

                    변수 :

                    <asp:Label ID="Label1" runat="server"><%# name %></asp:Label>

                    <br />

                    <br />

                    속성 :

                    <asp:Label ID="Label2" runat="server"><%# Name %></asp:Label>

                    <br />

                    <br />

                    텍스트박스(컨트롤) :

                    <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>

                    <br />

                    <br />

                    메서드 반환값 : <%# GetName() %>

                    <br />

                    <br />

                    텍스트박스(컨트롤속성) : <%# TextBox1.Text %>

                    <br />

                    <br />

                    <asp:Button ID="Button1" runat="server" Text="포스트백" Width="128px" />

&nbsp;<asp:Button ID="Button2" runat="server" Text="데이터바인딩 실행" Width="153px"

                           onclick="Button2_Click" />

             </h2>

             <p>

                    &nbsp;</p>

             <p>

                    &nbsp;</p>

             <p>

                    &nbsp;</p>

             <p>

                    &nbsp;</p>

             <p>

                    &nbsp;</p>

             <p>

                    &nbsp;</p>

             <p>

                    &nbsp;</p>

             <p>

                    &nbsp;</p>

             <br />

             <br />

   

    </div>

    </form>

</body>

</html>

 

 




using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

 

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

{

       //데이터소스 <- 거의 모든 종류의 데이터가 가능

       //1. 변수(클래스멤버)

       public string name = "홍길동";

 

       //2. 프로퍼티

       public string Name

       {

             get { return this.name + "입니다."; }

       }

 

       //3. 메서드

       public string GetName()

       {

             return this.name + "이라구요~";

       }

 

    protected void Page_Load(object sender, EventArgs e)

    {

            

    }

       protected void Button2_Click(object sender, EventArgs e)

       {

             //바인딩 실행

             // -> 해당 컨트롤.DataBind(); 실행

             //Label1.DataBind();

             //Label2.DataBind();

            

             this.DataBind();

 

             //Label1.Text = name;

       }

}

 






<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Ex33_DataBind.aspx.cs" Inherits="Ex33_DataBind" MaintainScrollPositionOnPostback="true" %>

 

<!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>

   

       <h2>

                    Ex33_DataBind.aspx</h2>

             <br />

             <h2>

                    이름을 선택하세요 :

                    <asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True"

                           onselectedindexchanged="DropDownList1_SelectedIndexChanged">

                    </asp:DropDownList>

                    <br />

                    <br />

                    <br />

                    <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>

             </h2>

             <br />

             <br />

             <br />

             <br />

   

    </div>

    </form>

</body>

</html>

 

 



using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

 

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

{

    protected void Page_Load(object sender, EventArgs e)

    {

             if (!IsPostBack)//초기화

             {

                    //컨트롤 초기화

                    //Bind1();

                    Bind2();

                    //Bind3();

             }

    }

 

       private void Bind3()

       {

             //1. 데이터 소스 (컬렉션)

             Dictionary<string, string> list = new Dictionary<string, string>();

 

             list.Add("홍길동", "뚱뚱이");

             list.Add("아무게", "비실이");

             list.Add("하하하", "먹보");

 

             //2. 바인딩

             // - list안의 1개 항목 != 단일데이터

             DropDownList1.DataSource = list;

             DropDownList1.DataTextField = "key";

             DropDownList1.DataValueField = "value";

 

             //3.

             DropDownList1.DataBind();

       }

 

       private void Bind1()

       {

             //1. 데이터 소스 (배열)

             string[] names = new string[3] { "홍길동", "아무게", "하하하" };

 

             //2. 컨트롤에 대입(출력)

             for (int i = 0; i < names.Length; i++)

             {

                    //DropDownList1.Items.Add(new ListItem("외관", "내부"));

                    //DropDownList1.Items.Add("문자열");

                    DropDownList1.Items.Add(new ListItem(names[i], i.ToString()));

             }

       }

 

       private void Bind2()

       {

             //1. 데이터 소스 (배열)

             string[] names = new string[3] { "홍길동", "아무게", "하하하" };

 

             //2. 데이터 소스 + 출력 컨트롤(Bind1() for문 역할)

             DropDownList1.DataSource = names;

 

             //3. DataBind() 호출

             DropDownList1.DataBind();

             //this.DataBind();//X

       }

 

      

 

       protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)

       {

             Label1.Text = DropDownList1.SelectedItem.Text + " : " + DropDownList1.SelectedItem.Value;

       }

}

 




<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Ex34_DataBind.aspx.cs" Inherits="Ex34_DataBind" MaintainScrollPositionOnPostback="true" %>

 

<!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>

   

       <h2>

                    Ex34_DataBind.aspx</h2>

             <br />

             <h3>

                    도서 구매 목록<br />

                    <br />

                    <asp:CheckBoxList ID="CheckBoxList1" runat="server">

                    </asp:CheckBoxList>

                    <br />

                    <br />

                    <asp:Button ID="Button1" runat="server" Text="구매하기" Width="140px" />

             </h3>

             <br />

             <br />

             <br />

   

    </div>

    </form>

</body>

</html>

 

 



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

{

    protected void Page_Load(object sender, EventArgs e)

    {

             //초기화

             if (!IsPostBack)

             {

                    //Bind1();

                    //Bind2();

                    Bind3();

             }

 

    }

 

       private void Bind1()

       {

             //비연결 vs 연결

             SqlConnection con = new SqlConnection();

             con.ConnectionString = "server=localhost;database=pubs;uid=sa;pwd=zangna1";

 

             SqlCommand cmd = new SqlCommand();

             cmd.Connection = con;

             cmd.CommandText = "select * from titles";

 

             con.Open();

            

             SqlDataReader reader = cmd.ExecuteReader();

 

             while (reader.Read())

             {

                    CheckBoxList1.Items.Add(new ListItem(reader["title"].ToString(), reader["title_id"].ToString()));

             }

 

             reader.Close();

             con.Close();

       }

 

       private void Bind2()

       {

             SqlConnection con = new SqlConnection();

             con.ConnectionString = "server=localhost;database=pubs;uid=sa;pwd=zangna1";

 

             SqlCommand cmd = new SqlCommand();

             cmd.Connection = con;

             cmd.CommandText = "select * from titles";

 

             con.Open();

 

             SqlDataReader reader = cmd.ExecuteReader();

 

             //바인딩

             CheckBoxList1.DataSource = reader;

             CheckBoxList1.DataTextField = "title";

             CheckBoxList1.DataValueField = "title_id";

 

             CheckBoxList1.DataBind();

 

             reader.Close();

             con.Close();

       }

 

       private void Bind3()

       {

             SqlDataAdapter adapter = new SqlDataAdapter("select * from titles", "server=localhost;database=pubs;uid=sa;pwd=zangna1");

             DataSet ds = new DataSet();

             adapter.Fill(ds, "titles");

 

             //데이터 소스 - DataSet

             CheckBoxList1.DataSource = ds.Tables["titles"];

             CheckBoxList1.DataTextField = "price";

             CheckBoxList1.DataTextFormatString = "$ {0:N2}";

             CheckBoxList1.DataValueField = "title_id";

 

             CheckBoxList1.DataBind();

       }

}

 










<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Ex36_DataBind.aspx.cs" Inherits="Ex36_DataBind" %>

 

<%@ Register src="Ex39.ascx" tagname="Ex39" 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>

   

       <h2>

                    Ex36_DataBind.aspx</h2>

             <br />

             <asp:CheckBoxList ID="CheckBoxList1" runat="server">

             </asp:CheckBoxList>

             <br />

             <br />

             <br />

             <br />

             <uc1:Ex39 ID="Ex391" runat="server" />

             <br />

             <br />

   

    </div>

    </form>

</body>

</html>

 

 


using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

 

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

{

    protected void Page_Load(object sender, EventArgs e)

    {

             if (!IsPostBack)

             {

                    pubsDataContext pubs = new pubsDataContext();

 

                    CheckBoxList1.DataSource = pubs.titles;

                    CheckBoxList1.DataTextField = "title";

                    CheckBoxList1.DataValueField = "title_id";

 

                    CheckBoxList1.DataBind();

             }

    }

}

 






using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

 

using System.Drawing;

using System.Drawing.Imaging;

 

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

{

    protected void Page_Load(object sender, EventArgs e)

    {

             //동적 이미지 생성 -> GDI+

             if (!IsPostBack)

             {

                    Response.Clear();

                    Response.ContentType = "image/jpeg";//MIME

 

                    //1. 이미지 객체 생성(메모리)

                    // - Bitmap : 래스터 이미지(png,gif,jpg,bmp..)

                    Bitmap img = new Bitmap(300, 200);

                    Graphics g = Graphics.FromImage(img);

 

                    //2. 이미지를 불러와서 새로운 이미지에 그리기

                    Bitmap img2 = new Bitmap(Server.MapPath("images/adore.png"));

 

                    //3. img에 배경색

                    g.FillRectangle(Brushes.White, 0, 0, 300, 200);

 

                    //4. 그림 그리기

                    g.DrawImage(img2, new Point(90, 20));

                    g.DrawString("이미지 테스트", new Font("굴림", 20.0F), Brushes.Blue, new Point(80, 130));

 

                    //5. 메모리상의 이미지를 클라이언트에게 직접 반환

                    // - Response.OutputStream : 임시페이지

                    img.Save(Response.OutputStream, ImageFormat.Jpeg);

 

             }

    }

}

 



<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Ex38_Path.aspx.cs" Inherits="Ex38_Path" %>

 

<%@ Register src="Ex39.ascx" tagname="Ex39" 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 style="font-size: x-small">

    <form id="form1" runat="server">

    <div>

   

       <h2>

                    Ex38_Path.aspx</h2>

             <strong>웹에서의 경로 표현<br />

                    <br />

                    1. 로컬 경로(서버측(C#)에서 작업하는 자원은 가능, 클라이언측 자원 불가능)<br />

                    <asp:Image ID="Image1" runat="server" ImageUrl="D:\I. usb\MS닷넷(KH)\Web\wwwroot\ASPNETEx\WebSite\images\adore.png" />

                    <br />

                    2. 상대 경로(현재 페이지 기준)<br />

                    <asp:Image ID="Image2" runat="server" ImageUrl="images/adore.png" />

                    <br />

                    <br />

                    <br />

                    3. ASP.NET 프로젝트 경로(프로젝트 루트 경로)<br />

                    <asp:Image ID="Image3" runat="server" ImageUrl="~/images/adore.png" />

                    <br />

                    <br />

                    <br />

                    4. 절대 경로<br />

                    <asp:Image ID="Image4" runat="server" ImageUrl="/ASPNETEx/WebSite/images/adore.png" />

                    <br />

                    <br />

                    <br />

                    5. 외부 경로<br />

                    </strong>

                    <asp:Image ID="Image5" runat="server" ImageUrl="http://localhost/ASPNETEx/WebSite/images/adore.png" />

             <p>

                    &nbsp;</p>

             <p>

                    &nbsp;</p>

             <p>

                    &nbsp;</p>

             <uc1:Ex39 ID="Ex391" runat="server" />

             <p>

                    &nbsp;</p>

             <p>

                    &nbsp;</p>

             <p>

                    &nbsp;</p>

             <p>

                    &nbsp;</p>

             <p>

                    &nbsp;</p>

             <br />

             <br />

   

    </div>

    </form>

</body>

</html>

 

 







유저컨트롤1

<%@ Control Language="C#" AutoEventWireup="true" CodeFile="Ex39.ascx.cs" Inherits="Ex39" %>

 

<hr style="width: 500px;" />

 

<p style="text-align: center;">

       &copy; Copyright 2012 KH All rights reserved.

</p>

 

 


유저컨트롤2

<%@ Control Language="C#" AutoEventWireup="true" CodeFile="Ex39_1.ascx.cs" Inherits="Ex39_1" %>

 

 

<%@ Register src="Ex39.ascx" tagname="Ex39" tagprefix="uc2" %>

 

<hr style="width: 500px;" />

 

<p style="text-align: center;">

       &copy; Copyright

       <asp:Label ID="LabelYear" runat="server"></asp:Label>       <asp:HyperLink ID="HyperLinkName" runat="server"></asp:HyperLink> All rights reserved.

</p>

<p style="text-align: center">

       &nbsp;</p>

 

 


유저컨트롤 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 Ex39_1 : System.Web.UI.UserControl

{

       //년도

       public string Year

       {

             set { this.LabelYear.Text = value; }

       }

 

       //회사명

       public string Name

       {

             set { HyperLinkName.Text = value; }

       }

 

       //회사링크

       public string URL

       {

             set { HyperLinkName.NavigateUrl = value; }

       }

 

    protected void Page_Load(object sender, EventArgs e)

    {

    }

}

 



aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Ex39_UserControl.aspx.cs" Inherits="Ex39_UserControl" %>

 

<%@ Register src="Ex39.ascx" tagname="Ex39" tagprefix="uc1" %>

 

<%@ Register src="Ex39_1.ascx" tagname="Ex39_1" 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>

       <style type="text/css">

             .style1

             {

                    font-weight: normal;

             }

             .style2

             {

                    font-size: small;

             }

             .style3

             {

                    font-weight: normal;

                    font-size: small;

             }

       </style>

</head>

<body>

    <form id="form1" runat="server">

    <div>

   

       <h2 class="style3">

                    Ex39_UserControl.aspx</h2>

             <h2 class="style1">

                    <span class="style2">- 자주 반복해서 사용되는 페이지의 일부 영역을 컨트롤 생성해서 재사용 가능</span><br

                           class="style2" />

                    <br class="style2" />

                    <span class="style2">- 메뉴, 로그인, 저작권.. </span><br class="style2" />

                    <br class="style2" />

                    <br class="style2" />

                    <span class="style2">ASP.NET의 유저 컨트롤</span><br class="style2" />

                    <br class="style2" />

                    <span class="style2">&nbsp;- *.ascx</span><br class="style2" />

                    <br class="style2" />

                    <span class="style2">&nbsp;- 단독으로 실행 불가능!!(*.aspx의 컨트롤로서 사용 가능)</span></h2>

             <h2 class="style1">

                    <asp:Button ID="Button1" runat="server" Text="Button" />

             </h2>

 

             <uc1:Ex39 ID="Ex391" runat="server" />

 

             <br />

 

             <uc2:Ex39_1 ID="Ex39_11" runat="server" Year="2012" Name="OO주식회사" URL="http://www.naver.com" />

 

             <uc2:Ex39_1 ID="Ex39_12" runat="server" Name="구글" URL="http://www.google.com"

                    Year="2013" />

             <br />

             <br />

             <br />

             <br />

             <br />

             <br />

             <br />

             <br />

 

            

   

    </div>

    </form>

       <p style="text-align: center">

             &nbsp;</p>

       <p style="text-align: center">

             &nbsp;</p>

       <p style="text-align: center">

             &nbsp;</p>

       <p style="text-align: center">

             &nbsp;</p>

</body>

</html>

 

 

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

{

    protected void Page_Load(object sender, EventArgs e)

    {

             this.Button1.Text = "안녕";

    }

}

 



aspx 컴파일 -> 컴파일한 결과 값이 어딘가에 존재한다.
컨트롤 + f5 = 빌드되면서 컴파일이되고 실행된다.
비쥬얼스튜디오에 c#파일에서 수정되면 비쥬얼스튜디오를 실행하지 않아도 웹에서 수정된 페이지가 보여진다. 그렇다는건 이미 어딘가에 컴파일되어 다시 올라가 있다는 것이다.
dll실행기가 가장 먼저하는일 0단계 객체를 만들때 만드는 기준은 컴파일된 파일 컨트롤 + f5는 실행하는 단계이다. dll은 .cs 파일중 컴파일한 결과가 있는지 없는지 확인한다. 임시폴더에 저장함 컴파일된 파일을 이기준으로 0~8단계를 싱행하는것 
앞에 만들어놓았던 dll파일을 가지고 임시파일을 돌려준다. .aspx가 속도가 굉장히 빠르다. 컴파일된 웹사이트는 별로 없다. 컴파일 이후 요청부터는 속도가 엄청 빠르다. 단 첫번째 요청하는 사람은 굉장히 느리다. 수정이 되었다면 기존에 컴파일된 dll을 파괴하고 다시 실행파일을 만든다.

반응형