login register Sysop! about ME  
qrcode
    최초 작성일 :    2008년 04월 02일
  최종 수정일 :    2008년 04월 07일
  작성자 :    neostyx
  편집자 :    엔틱스(최 지훈)
  읽음수 :    30,202

강좌 목록으로 돌아가기

필자의 잡담~

안녕하세요. ^^;; 이번에 새롭게 태오사이트에 강좌를 연재하게 된 엔틱스입니다. ^^;;
개발자라면 누구나 알고 있는 유명한 사이트인 태오사이트에 연재를 하게 되어서 상당한 영광이라고 생각하며, 많은 도움이 될 수 있도록 열심히 노력하겠습니다. ^^;;

안녕하세요. 엔틱스입니다. 지난 아티클인 ListView 컨트롤 Part1에 이어 이번 ListView 컨트롤 Part2에서는 Part1에서 설명드리지 못한 템플릿인, SelectedItemTemplate 템플릿, EditItemTemplate 템플릿, 그리고 InsertItemTemplate 템플릿에 대한 설명을 드리도록 하겠습니다.

ListView 컨트롤 Part2에서 설명하게 되는 이들 템플릿은 ListView 컨트롤을 이용한 선택(Select), 편집(Edit), 삽입(Insert), 삭제(Delete), 업데이트(Update)등에 사용되는 템플릿이며, ASP.NET 2.0에서 사용하던 GridView 컨트롤의 기능과 유사하게 동작하게 됩니다. 이들 템플릿을 사용하기 위해서는 ListView 컨트롤에 연결되는 DataSource 컨트롤로써, SqlDataSource 컨트롤을 이용하도록 하겠습니다.

먼저, 도구 상자의 데이터 탭에서 SqlDataSource 컨트롤을 웹 폼으로 드래그 앤 드랍시킵니다. 그 후에 SqlDataSource 컨트롤의 스마트 태그의 메뉴 중 "데이터 소스 구성(Configurate Data Source...)" 메뉴를 이용하여, 데이터 소스를 구성하도록 합니다. 데이터 소스 구성 마법사 창이 아래와 같이 나타나면, 데이터베이스에 연결할 연결 문자열을 정의합니다.

"다음(Next)" 버튼을 클릭하면, 추가한 연결 문자열을 구성 파일(Web.Config)에 저장하겠냐고 물어보게 됩니다. 체크박스에 체크를 한 후에 "다음(Next)" 버튼을 클릭하게 되면, Select 문을 구성할 수 있는 창이 뜨게 됩니다. 저의 경우는 Products 테이블만을 사용할 것이므로, Products 테이블을 선택한 후, 아래의 그림과 같이 컬럼을 선택합니다. 또한, "Order By..." 버튼을 클릭하여, ProductID를 내림차순 정렬로 변경합니다.

"고급(Advanced...)" 버튼을 클릭하여 나타나는 창에서, "INSERT, UPDATE 그리고 DELETE 문 등록(Generate INSERT, UPDATE and DELETE Statements)"의 체크박스를 체크한 후, "확인(OK)" 버튼을 클릭합니다.

다음으로는 쿼리를 테스트하는 창이 나타나게 됩니다. "쿼리 테스트(Test Query)" 버튼을 클릭하여 화면에 출력할 데이터를 먼저 검색한 후, "마침(Finish)" 버튼을 클릭하여 데이터 소스 구성 마법사를 종료합니다.

데이터 소스 구성 마법사를 이용하여 변경된 SqlDataSource 컨트롤의 구문은 다음과 같게 됩니다.

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

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

      SelectCommand="SELECT [ProductName], [CategoryID], [QuantityPerUnit], [UnitPrice], [ProductID] FROM [Products] ORDER BY [ProductID] DESC"

      DeleteCommand="DELETE FROM [Products] WHERE [ProductID] = @ProductID"

      InsertCommand="INSERT INTO [Products] ([ProductName], [CategoryID], [QuantityPerUnit], [UnitPrice]) VALUES (@ProductName, @CategoryID, @QuantityPerUnit, @UnitPrice)"

      UpdateCommand="UPDATE [Products] SET [ProductName] = @ProductName, [CategoryID] = @CategoryID, [QuantityPerUnit] = @QuantityPerUnit, [UnitPrice] = @UnitPrice WHERE [ProductID] = @ProductID">

      <DeleteParameters>

        <asp:Parameter Name="ProductID" Type="Int32" />

      </DeleteParameters>

      <UpdateParameters>

        <asp:Parameter Name="ProductName" Type="String" />

        <asp:Parameter Name="CategoryID" Type="Int32" />

        <asp:Parameter Name="QuantityPerUnit" Type="String" />

        <asp:Parameter Name="UnitPrice" Type="Decimal" />

        <asp:Parameter Name="ProductID" Type="Int32" />

      </UpdateParameters>

      <InsertParameters>

        <asp:Parameter Name="ProductName" Type="String" />

        <asp:Parameter Name="CategoryID" Type="Int32" />

        <asp:Parameter Name="QuantityPerUnit" Type="String" />

        <asp:Parameter Name="UnitPrice" Type="Decimal" />

      </InsertParameters>

    </asp:SqlDataSource>

이제, 데이터를 출력하고 추가/수정/삭제의 기능을 제공하는 ListView 컨트롤을 도구 상자의 데이터 탭에서 웹 폼으로 드래그 앤 드랍한 후, ListView 컨트롤의 스마트 태그의 메뉴에서 데이터 소스를 위에서 정의한 SqlDataSource로 선택합니다. 그 후 다시 ListView 컨트롤의 스마트 태그 메뉴에서 "ListView 구성(Configurate ListView...)" 메뉴를 선택하여 ListView 컨트롤을 구성하는 마법사를 실행합니다. ListView 컨트롤을 구성하는 마법사 창이 뜨게 되면, 아래의 화면과 같이 레이아웃과 스타일을 선택 후, 옵션의 수정(Editing), 삽입(Inserting), 삭제(Deleting) 가능의 체크 박스를 체크해준 후, "확인(OK)" 버튼을 클릭하여, ListView 컨트롤의 구성을 종료합니다.

ListView 컨트롤을 구성하는 마법사를 이용하면, 자동적으로 ListView 컨트롤에 각 템플릿들이 추가되게 되며, 이번 강좌에서 설명할 SelectedItemTemplate 템플릿, EditItemTemplate 템플릿, 그리고 InsertItemTemplate 템플릿이 추가된 것을 아래의 소스에서 확인할 수 있습니다.

    <asp:ListView ID="ListView1" runat="server" DataSourceID="SqlDataSource1" DataKeyNames="ProductID" InsertItemPosition="FirstItem">

      <AlternatingItemTemplate>

        <tr style="background-color:#FFF8DC;">

          <td>

            <asp:Button ID="DeleteButton" runat="server" CommandName="Delete" Text="Delete" />

            <asp:Button ID="EditButton" runat="server" CommandName="Edit" Text="Edit" />

          </td>

          <td>

            <asp:Label ID="ProductNameLabel" runat="server" Text='<%# Eval("ProductName") %>' />

          </td>

          <td>

            <asp:Label ID="CategoryIDLabel" runat="server" Text='<%# Eval("CategoryID") %>' />

          </td>

          <td>

            <asp:Label ID="QuantityPerUnitLabel" runat="server" Text='<%# Eval("QuantityPerUnit") %>' />

          </td>

          <td>

            <asp:Label ID="UnitPriceLabel" runat="server" Text='<%# Eval("UnitPrice") %>' />

          </td>

          <td>

            <asp:Label ID="ProductIDLabel" runat="server" Text='<%# Eval("ProductID") %>' />

          </td>

        </tr>

      </AlternatingItemTemplate>

      <LayoutTemplate>

        <table runat="server">

          <tr runat="server">

            <td runat="server">

              <table ID="itemPlaceholderContainer" runat="server" border="1"

                style="background-color: #FFFFFF;border-collapse: collapse;border-color: #999999;border-style:none;border-width:1px;font-family: Verdana, Arial, Helvetica, sans-serif;">

                <tr runat="server" style="background-color:#DCDCDC;color: #000000;">

                  <th runat="server"></th>

                  <th runat="server">ProductName</th>

                  <th runat="server">CategoryID</th>

                  <th runat="server">QuantityPerUnit</th>

                  <th runat="server">UnitPrice</th>

                  <th runat="server">ProductID</th>

                </tr>

                <tr ID="itemPlaceholder" runat="server">

                </tr>

              </table>

            </td>

          </tr>

          <tr runat="server">

            <td runat="server" style="text-align: center;background-color: #CCCCCC;font-family: Verdana, Arial, Helvetica, sans-serif;color: #000000;">

            </td>

          </tr>

        </table>

      </LayoutTemplate>

      <InsertItemTemplate>

        <tr style="">

          <td>

            <asp:Button ID="InsertButton" runat="server" CommandName="Insert" Text="Insert" />

            <asp:Button ID="CancelButton" runat="server" CommandName="Cancel" Text="Clear" />

          </td>

          <td>

            <asp:TextBox ID="ProductNameTextBox" runat="server" Text='<%# Bind("ProductName") %>' />

          </td>

          <td>

            <asp:TextBox ID="CategoryIDTextBox" runat="server" Text='<%# Bind("CategoryID") %>' />

          </td>

          <td>

            <asp:TextBox ID="QuantityPerUnitTextBox" runat="server" Text='<%# Bind("QuantityPerUnit") %>' />

          </td>

          <td>

            <asp:TextBox ID="UnitPriceTextBox" runat="server" Text='<%# Bind("UnitPrice") %>' />

          </td>

          <td>&nbsp;</td>

        </tr>

      </InsertItemTemplate>

      <SelectedItemTemplate>

        <tr style="background-color:#008A8C;font-weight: bold;color: #FFFFFF;">

          <td>

            <asp:Button ID="DeleteButton" runat="server" CommandName="Delete" Text="Delete" />

            <asp:Button ID="EditButton" runat="server" CommandName="Edit" Text="Edit" />

          </td>

          <td>

            <asp:Label ID="ProductNameLabel" runat="server" Text='<%# Eval("ProductName") %>' />

          </td>

          <td>

            <asp:Label ID="CategoryIDLabel" runat="server" Text='<%# Eval("CategoryID") %>' />

          </td>

          <td>

            <asp:Label ID="QuantityPerUnitLabel" runat="server" Text='<%# Eval("QuantityPerUnit") %>' />

          </td>

          <td>

            <asp:Label ID="UnitPriceLabel" runat="server" Text='<%# Eval("UnitPrice") %>' />

          </td>

          <td>

            <asp:Label ID="ProductIDLabel" runat="server" Text='<%# Eval("ProductID") %>' />

          </td>

        </tr>

      </SelectedItemTemplate>

      <EmptyDataTemplate>

        <table runat="server"

          style="background-color: #FFFFFF;border-collapse: collapse;border-color: #999999;border-style:none;border-width:1px;">

          <tr>

            <td>No data was returned.</td>

          </tr>

        </table>

      </EmptyDataTemplate>

      <EditItemTemplate>

        <tr style="background-color:#008A8C;color: #FFFFFF;">

          <td>

            <asp:Button ID="UpdateButton" runat="server" CommandName="Update" Text="Update" />

            <asp:Button ID="CancelButton" runat="server" CommandName="Cancel" Text="Cancel" />

          </td>

          <td>

            <asp:TextBox ID="ProductNameTextBox" runat="server" Text='<%# Bind("ProductName") %>' />

          </td>

          <td>

            <asp:TextBox ID="CategoryIDTextBox" runat="server" Text='<%# Bind("CategoryID") %>' />

          </td>

          <td>

            <asp:TextBox ID="QuantityPerUnitTextBox" runat="server" Text='<%# Bind("QuantityPerUnit") %>' />

          </td>

          <td>

            <asp:TextBox ID="UnitPriceTextBox" runat="server" Text='<%# Bind("UnitPrice") %>' />

          </td>

          <td>

            <asp:Label ID="ProductIDLabel1" runat="server" Text='<%# Eval("ProductID") %>' />

          </td>

        </tr>

      </EditItemTemplate>

      <ItemTemplate>

        <tr style="background-color:#DCDCDC;color: #000000;">

          <td>

            <asp:Button ID="DeleteButton" runat="server" CommandName="Delete" Text="Delete" />

            <asp:Button ID="EditButton" runat="server" CommandName="Edit" Text="Edit" />

          </td>

          <td>

            <asp:Label ID="ProductNameLabel" runat="server" Text='<%# Eval("ProductName") %>' />

          </td>

          <td>

            <asp:Label ID="CategoryIDLabel" runat="server" Text='<%# Eval("CategoryID") %>' />

          </td>

          <td>

            <asp:Label ID="QuantityPerUnitLabel" runat="server" Text='<%# Eval("QuantityPerUnit") %>' />

          </td>

          <td>

            <asp:Label ID="UnitPriceLabel" runat="server" Text='<%# Eval("UnitPrice") %>' />

          </td>

          <td>

            <asp:Label ID="ProductIDLabel" runat="server" Text='<%# Eval("ProductID") %>' />

          </td>

        </tr>

      </ItemTemplate>

    </asp:ListView>

주의
위의 소스에서 볼 수 있다시피, EditItemTemplate 템플릿과 InsertItemTemplate 템플릿에서 사용되는 TextBox 컨트롤의 Text 속성은 Eval() 메소드가 아닌, Bind() 메소드를 사용하고 있습니다. 이는, Eval() 메소드의 경우는 읽기 전용 단방향 바인딩을 정의하기에, 데이터의 추가 또는 수정 시에는 값을 반영할 수 없기 때문이며, 이 경우에는 양방향 바인딩을 제공하는 Bind() 메소드를 사용해야만 가능하기 때문입니다. (참고 : http://msdn2.microsoft.com/ko-kr/library/ms178366.aspx)
또한, ListView에서 데이터를 추가할 경우, 추가할 항목이 나타나는 위치를 지정하는데 사용하기 위한 속성인 InsertItemPosition의 값은 FirstItem, LastItem, None 중 하나를 선택할 수 있으며, 새로 추가되는 값을 바로 확인하기 위해서 이 속성의 값을 FirstItem으로 지정하였습니다.

구성된 ListView 컨트롤을 브라우저에서 보면 아래의 그림과 같이 데이터가 출력됩니다.

새로운 값을 Products 테이블에 추가하기 위해, 데이터를 입력한 후에 좌측의 "Insert" 버튼을 클릭하면, 입력된 데이터의 값이 화면에 출력됩니다.

또한, 새로이 추가된 값을 변경하기 위해, "Edit" 버튼을 클릭하면 EditItemTemplate 템플릿에 정의된 코드가 화면에 보이게 되며, "Cancel" 버튼을 클릭하면 이전 화면으로, "Update" 버튼을 클릭하면, 수정된 값이 적용되어 화면에 표시되게 됩니다.

"Delete" 버튼을 클릭하면, 모두들 예상하셨다시피 선택한 행의 데이터가 삭제됩니다.

이로써 ListView 컨트롤을 이용한 데이터의 추가, 수정, 삭제에 대한 방법을 알아보았습니다. 여기에서는 SelectedItemTemplate 템플릿에 정의된 내용을 사용하는 방법에 대해서 특별히 설명하지는 않았지만, ItemTemplate 템플릿 또는, AlternatingItemTemplate 템플릿에 CommandName이 "Select"인 Button 컨트롤을 추가한 후 Button 컨트롤을 누르게 되면, Button 컨트롤이 위치한 행이 선택되게 됩니다.

이상으로, ListView 컨트롤에서 사용되는 템플릿에 대한 설명을 마치도록 하겠습니다. ListView 컨트롤을 사용하는 방법에 대해서 좀 더 알고 싶으신 분은 MSDN( http://msdn2.microsoft.com/ko-kr/library/system.web.ui.webcontrols.listview.aspx )을 참고하시기 바랍니다.


authored by


 
 
.NET과 Java 동영상 기반의 교육사이트

로딩 중입니다...

서버 프레임워크 지원 : NeoDEEX
based on ASP.NET 3.5
Creative Commons License
{5}
{2} 읽음   :{3} ({4})