DataGrid 클래스
업데이트: 2007년 11월
테이블에 데이터 소스의 항목을 표시하는 데이터 바인딩 목록 컨트롤입니다. DataGrid 컨트롤을 사용하면 이러한 항목을 선택, 정렬 및 편집할 수 있습니다.
어셈블리: System.Web(System.Web.dll)
[AspNetHostingPermissionAttribute(SecurityAction.LinkDemand, Level = AspNetHostingPermissionLevel.Minimal)] [AspNetHostingPermissionAttribute(SecurityAction.InheritanceDemand, Level = AspNetHostingPermissionLevel.Minimal)] public class DataGrid : BaseDataList, INamingContainer
/** @attribute AspNetHostingPermissionAttribute(SecurityAction.LinkDemand, Level = AspNetHostingPermissionLevel.Minimal) */ /** @attribute AspNetHostingPermissionAttribute(SecurityAction.InheritanceDemand, Level = AspNetHostingPermissionLevel.Minimal) */ public class DataGrid extends BaseDataList implements INamingContainer
public class DataGrid extends BaseDataList implements INamingContainer
<asp:DataGrid />
DataGrid 컨트롤을 사용하여 데이터 소스의 필드를 테이블의 열로 표시합니다. DataGrid 컨트롤에 있는 각 행은 데이터 소스의 레코드를 나타냅니다. DataGrid 컨트롤은 선택, 편집, 삭제, 페이징 및 정렬을 지원합니다.
열 형식에 따라 컨트롤에 있는 열의 동작이 결정됩니다. 다음 표에서는 사용할 수 있는 여러 열 형식을 보여 줍니다.
열 형식 | 설명 |
|---|---|
데이터 소스의 필드에 바인딩된 열을 표시합니다. 필드에 있는 각 항목을 텍스트로 표시합니다. 이 열 클래스는 DataGrid 컨트롤의 기본 열 형식입니다. | |
열에 있는 각 항목의 명령 단추를 표시하는 열입니다. 이 열 클래스를 사용하여 Add 또는 Remove 단추 같은 사용자 지정 단추 컨트롤의 열을 만들 수 있습니다. | |
열에 있는 각 항목에 대한 편집 명령이 들어 있는 열입니다. | |
열에 있는 각 항목의 내용을 하이퍼링크로 표시합니다. 열의 내용은 데이터 소스나 정적 텍스트의 필드에 바인딩될 수 있습니다. | |
지정된 템플릿 다음에 오는 열에 있는 각 항목을 표시합니다. 이 열 클래스를 사용하면 열에 사용자 지정 컨트롤을 제공할 수 있습니다. |
기본적으로 AutoGenerateColumns 속성은 true로 설정되기 때문에 데이터 소스의 각 필드에 대해 BoundColumn 개체가 만들어집니다. 그런 다음 각 필드는 데이터 소스에 표시된 순서대로 DataGrid 컨트롤에 있는 열로 렌더링됩니다.
또한 AutoGenerateColumns 속성을 false로 설정한 다음 열고 닫는 <Columns> 태그 사이에 포함할 열을 나열하여 DataGrid 컨트롤에 표시할 열을 수동으로 제어할 수도 있습니다. 지정된 열은 나열된 순서대로 Columns 컬렉션에 추가됩니다. 이렇게 하면 DataGrid 컨트롤에 있는 열을 프로그래밍 방식으로 제어할 수 있습니다.
참고: |
|---|
열이 DataGrid 컨트롤에 표시되는 순서는 열이 Columns 컬렉션에 표시되는 순서에 의해 제어됩니다. Columns 컬렉션을 조작하여 열의 순서를 프로그래밍 방식으로 변경할 수는 있지만 원하는 표시 순서대로 열을 나열하는 것이 보다 쉽습니다. |
명시적으로 선언된 열을 자동으로 생성된 열과 함께 표시할 수 있습니다. 두 열을 모두 사용하는 경우 명시적으로 선언된 열이 먼저 렌더링되고 그 다음에 자동으로 생성된 열이 렌더링됩니다.
참고: |
|---|
자동으로 생성된 열은 Columns 컬렉션에 추가되지 않습니다. |
DataGrid 컨트롤의 모양은 해당 컨트롤의 다른 부분에 대한 스타일 속성을 설정하여 사용자가 지정할 수 있습니다. 다음 표에서는 여러 가지 스타일 속성을 보여 줍니다.
스타일 속성 | 설명 |
|---|---|
DataGrid 컨트롤에 있는 대체 항목의 스타일을 지정합니다. | |
DataGrid 컨트롤에서 편집하고 있는 항목의 스타일을 지정합니다. | |
DataGrid 컨트롤에 있는 바닥글 구역의 스타일을 지정합니다. | |
DataGrid 컨트롤에 있는 머리글 구역의 스타일을 지정합니다. | |
DataGrid 컨트롤에 있는 항목의 스타일을 지정합니다. | |
DataGrid 컨트롤에 있는 페이지 선택 구역의 스타일을 지정합니다. | |
DataGrid 컨트롤에서 선택한 항목의 스타일을 지정합니다. |
컨트롤의 다른 부분을 표시하거나 숨길 수도 있습니다. 다음 표에서는 표시하거나 숨길 부분을 제어하는 속성을 보여 줍니다.
속성 | 설명 |
|---|---|
DataGrid 컨트롤의 바닥글 구역을 표시하거나 숨깁니다. | |
DataGrid 컨트롤의 머리글 구역을 표시하거나 숨깁니다. |
브라우저에 있는 컨트롤에 의해 렌더링된 <td> 및 <tr> 태그에 특성을 프로그래밍 방식으로 추가하여 DataGrid 컨트롤의 모양을 제어할 수도 있습니다. OnItemCreated 또는 OnItemDataBound 이벤트에 대한 이벤트 처리기에 코드를 제공하여 프로그래밍 방식으로 특성을 추가할 수 있습니다.
<td> 태그에 특성을 추가하려면 먼저 특성을 추가할 DataGrid 컨트롤의 셀을 나타내는 TableCell 개체를 가져옵니다. 원하는 TableCell 개체를 가져오려면 이벤트 처리기에 전달된 DataGridItemEventArgs 개체의 Item 속성에 대한 Control.Controls 컬렉션을 사용하면 됩니다. 그런 다음 TableCell 개체에 대한 Attributes 컬렉션의 AttributeCollection.Add 메서드를 사용하여 <td> 태그에 특성을 추가할 수 있습니다.
<tr> 태그에 특성을 추가하려면 먼저 특성을 추가할 DataGrid 컨트롤의 행을 나타내는 DataGridItem 개체를 가져옵니다. 원하는 DataGridItem 개체를 가져오려면 이벤트 처리기에 전달된 DataGridItemEventArgs 개체의 Item 속성을 사용하면 됩니다. 그런 다음 DataGridItem 개체에 대한 Attributes 컬렉션의 AttributeCollection.Add 메서드를 사용하여 <tr> 태그에 특성을 추가할 수 있습니다.
주의: |
|---|
이 컨트롤은 악의적인 클라이언트 스크립트가 포함되어 있을 가능성이 있는 사용자 입력을 표시하는 데 사용할 수 있습니다. 클라이언트에서 보낸 정보를 응용 프로그램에 표시하기 전에 해당 정보에서 실행 스크립트, SQL 문 또는 기타 코드를 확인합니다. ASP.NET은 사용자 입력의 스크립트 및 HTML을 차단하도록 입력 요청 유효성 검사 기능을 제공합니다. 사용자 입력을 평가하기 위해 유효성 검사 서버 컨트롤도 제공됩니다. 자세한 내용은 유효성 검사 서버 컨트롤 구문을 참조하십시오. |
액세스 가능성
이 컨트롤에 대해 기본적으로 렌더링되는 태그는 WCAG(Web Content Accessibility Guidelines) 1.0 우선 순위 1 지침과 같은 내게 필요한 옵션 표준을 따르지 않을 수도 있습니다. 이 컨트롤의 내게 필요한 옵션 지원에 대한 자세한 내용은 ASP.NET 컨트롤 및 내게 필요한 옵션을 참조하십시오.
다음 코드 예제에서는 DataGrid 컨트롤을 사용하여 데이터 소스의 항목을 표시하는 방법을 보여 줍니다.
<%@ Page Language="C#" AutoEventWireup="True" %> <%@ Import Namespace="System.Data" %> <!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" > <script language="C#" runat="server"> ICollection CreateDataSource() { DataTable dt = new DataTable(); DataRow dr; dt.Columns.Add(new DataColumn("IntegerValue", typeof(Int32))); dt.Columns.Add(new DataColumn("StringValue", typeof(string))); dt.Columns.Add(new DataColumn("CurrencyValue", typeof(double))); for (int i = 0; i < 9; i++) { dr = dt.NewRow(); dr[0] = i; dr[1] = "Item " + i.ToString(); dr[2] = 1.23 * (i + 1); dt.Rows.Add(dr); } DataView dv = new DataView(dt); return dv; } void Page_Load(Object sender, EventArgs e) { if (!IsPostBack) { // Load this data only once. ItemsGrid.DataSource= CreateDataSource(); ItemsGrid.DataBind(); } } </script> <head runat="server"> <title>DataGrid Example</title> </head> <body> <form id="form1" runat="server"> <h3>DataGrid Example</h3> <b>Product List</b> <asp:DataGrid id="ItemsGrid" BorderColor="black" BorderWidth="1" CellPadding="3" AutoGenerateColumns="true" runat="server"> <HeaderStyle BackColor="#00aaaa"> </HeaderStyle> </asp:DataGrid> </form> </body> </html>
다음 코드 예제에서는 간단한 장바구니에 대한 DataGrid 컨트롤을 사용하는 방법을 보여 줍니다.
<%@ Page Language="C#" AutoEventWireup="True" %> <%@ Import Namespace="System.Data" %> <!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" > <script language="C#" runat="server"> DataTable Cart; DataView CartView; ICollection CreateDataSource() { DataTable dt = new DataTable(); DataRow dr; dt.Columns.Add(new DataColumn("IntegerValue", typeof(Int32))); dt.Columns.Add(new DataColumn("StringValue", typeof(string))); dt.Columns.Add(new DataColumn("CurrencyValue", typeof(double))); for (int i = 0; i < 9; i++) { dr = dt.NewRow(); dr[0] = i; dr[1] = "Item " + i.ToString(); dr[2] = 1.23 * (i + 1); dt.Rows.Add(dr); } DataView dv = new DataView(dt); return dv; } void Page_Load(Object sender, EventArgs e) { if (Session["DG4_ShoppingCart"] == null) { Cart = new DataTable(); Cart.Columns.Add(new DataColumn("Item", typeof(string))); Cart.Columns.Add(new DataColumn("Price", typeof(string))); Session["DG4_ShoppingCart"] = Cart; } else { Cart = (DataTable)Session["DG4_ShoppingCart"]; } CartView = new DataView(Cart); ShoppingCart.DataSource = CartView; ShoppingCart.DataBind(); if (!IsPostBack) { // Load this data only once. ItemsGrid.DataSource= CreateDataSource(); ItemsGrid.DataBind(); } } void Grid_CartCommand(Object sender, DataGridCommandEventArgs e) { DataRow dr = Cart.NewRow(); // e.Item is the table row where the command is raised. // For bound columns, the value is stored in the Text property of the TableCell. TableCell itemCell = e.Item.Cells[2]; TableCell priceCell = e.Item.Cells[3]; string item = itemCell.Text; string price = priceCell.Text; if (((Button)e.CommandSource).CommandName == "AddToCart") { dr[0] = item; dr[1] = price; Cart.Rows.Add(dr); } else { // Remove from Cart. CartView.RowFilter = "Item='" + item + "'"; if (CartView.Count > 0) { CartView.Delete(0); } CartView.RowFilter = ""; } ShoppingCart.DataBind(); } </script> <head runat="server"> <title>DataGrid Example</title> </head> <body> <form id="form1" runat="server"> <h3>DataGrid Example</h3> <table cellpadding="5"> <tr valign="top"> <td> <b>Product List</b> <asp:DataGrid id="ItemsGrid" BorderColor="black" BorderWidth="1" CellPadding="3" AutoGenerateColumns="false" OnItemCommand="Grid_CartCommand" runat="server"> <HeaderStyle BackColor="#00aaaa"> </HeaderStyle> <Columns> <asp:ButtonColumn HeaderText="Add to cart" ButtonType="PushButton" Text="Add" CommandName="AddToCart" /> <asp:ButtonColumn HeaderText="Remove from cart" ButtonType="PushButton" Text="Remove" CommandName="RemoveFromCart" /> <asp:BoundColumn HeaderText="Item" DataField="StringValue"/> <asp:BoundColumn HeaderText="Price" DataField="CurrencyValue" DataFormatString="{0:c}"> <ItemStyle HorizontalAlign="right"> </ItemStyle> </asp:BoundColumn> </Columns> </asp:DataGrid> </td> <td> <b>Shopping Cart</b> <asp:DataGrid id="ShoppingCart" runat="server" BorderColor="black" BorderWidth="1" GridLines="Both" ShowFooter="false" CellPadding="3" CellSpacing="0"> <HeaderStyle BackColor="#00aaaa"> </HeaderStyle> </asp:DataGrid> </td> </tr> </table> </form> </body> </html>
다음 코드 예제에서는 DataGrid 컨트롤을 통해 생성된 <td> 및 <tr> 태그에 동적으로 특성을 추가하는 방법을 보여 줍니다.
<%@ Page Language="C#" AutoEventWireup="True" %> <%@ Import Namespace="System.Data" %> <!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" > <script runat="server"> ICollection CreateDataSource() { DataTable dt = new DataTable(); DataRow dr; dt.Columns.Add(new DataColumn("IntegerValue", typeof(Int32))); dt.Columns.Add(new DataColumn("StringValue", typeof(string))); dt.Columns.Add(new DataColumn("CurrencyValue", typeof(double))); for (int i = 0; i < 5; i++) { dr = dt.NewRow(); dr[0] = i; dr[1] = "Item " + i.ToString(); dr[2] = 1.23 * (i+1); dt.Rows.Add(dr); } DataView dv = new DataView(dt); return dv; } void Page_Load(Object sender, EventArgs e) { if (!IsPostBack) { // Load this data only once. ItemsGrid.DataSource = CreateDataSource(); ItemsGrid.DataBind(); } } void Item_Bound(Object sender, DataGridItemEventArgs e) { ListItemType itemType = (ListItemType)e.Item.ItemType; if ((itemType != ListItemType.Header) && (itemType != ListItemType.Footer) && (itemType != ListItemType.Separator)) { // Get the IntegerValue cell from the grid's column collection. TableCell intCell = (TableCell)e.Item.Controls[0]; // Add attributes to the cell. intCell.Attributes.Add("id", "intCell" + e.Item.ItemIndex.ToString()); intCell.Attributes.Add("OnClick", "Update_intCell" + e.Item.ItemIndex.ToString() + "()"); // Add attributes to the row. e.Item.Attributes.Add("id", "row" + e.Item.ItemIndex.ToString()); e.Item.Attributes.Add("OnDblClick", "Update_row" + e.Item.ItemIndex.ToString() + "()"); } } </script> <script type="text/vbscript"> sub Update_intCell0 Alert "You Selected Cell 0." end sub sub Update_intCell1 Alert "You Selected Cell 1." end sub sub Update_intCell2 Alert "You Selected Cell 2." end sub sub Update_intCell3 Alert "You Selected Cell 3." end sub sub Update_intCell4 Alert "You Selected Cell 4." end sub sub UpDate_row0 Alert "You selected the row 0." end sub sub UpDate_row1 Alert "You selected the row 1." end sub sub UpDate_row2 Alert "You selected the row 2." end sub sub UpDate_row3 Alert "You selected the row 3." end sub sub UpDate_row4 Alert "You selected the row 4." end sub </script> <head runat="server"> <title> Adding Attributes to the <td> and <tr> </title> </head> <body> <form id="form1" runat="server"> <h3> Adding Attributes to the <td> and <tr> <br /> Tags of a DataGrid Control </h3> <asp:DataGrid id="ItemsGrid" runat="server" BorderColor="black" BorderWidth="1" CellPadding="3" ShowFooter="true" OnItemDataBound="Item_Bound" AutoGenerateColumns="false"> <HeaderStyle BackColor="#00aaaa"> </HeaderStyle> <FooterStyle BackColor="#00aaaa"> </FooterStyle> <Columns> <asp:BoundColumn HeaderText="Number" DataField="IntegerValue"> <ItemStyle BackColor="yellow"> </ItemStyle> </asp:BoundColumn> <asp:BoundColumn HeaderText="Item" DataField="StringValue"/> <asp:BoundColumn HeaderText="Price" DataField="CurrencyValue" DataFormatString="{0:c}"> <ItemStyle HorizontalAlign="right"> </ItemStyle> </asp:BoundColumn> </Columns> </asp:DataGrid> <br /><br /> Click on one of the cells in the <b>Number</b> column to select the cell. <br /><br /> Double click on a row to select a row. </form> </body> </html>
<%@ Page Language="C#" AutoEventWireup="True" %> <%@ Import Namespace="System.Data" %> <!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" > <script runat="server"> ICollection CreateDataSource() { // Create sample data for the DataGrid control. DataTable dt = new DataTable(); DataRow dr; // Define the columns of the table. dt.Columns.Add(new DataColumn("IntegerValue", typeof(Int32))); dt.Columns.Add(new DataColumn("StringValue", typeof(string))); dt.Columns.Add(new DataColumn("CurrencyValue", typeof(double))); // Populate the table with sample values. for (int i = 0; i < 9; i++) { dr = dt.NewRow(); dr[0] = i; dr[1] = "Item " + i.ToString(); dr[2] = 1.23 * (i + 1); dt.Rows.Add(dr); } DataView dv = new DataView(dt); return dv; } void Page_Load(Object sender, EventArgs e) { // Load sample data only once when the page is first loaded. if (!IsPostBack) { ItemsGrid.DataSource = CreateDataSource(); ItemsGrid.DataBind(); } } void Button_Click(Object sender, EventArgs e) { // Count the number of selected items in the DataGrid control. int count = 0; // Display the selected times. Message.Text = "You Selected: <br />"; // Iterate through each item (row) in the DataGrid control and // determine whether it is selected. foreach (DataGridItem item in ItemsGrid.Items) { DetermineSelection(item, ref count); } // If no items are selected, display the appropriate message. if (count == 0) { Message.Text = "No items selected"; } } void DetermineSelection(DataGridItem item, ref int count) { // Retrieve the SelectCheckBox CheckBox control from the specified // item (row) in the DataGrid control. CheckBox selection = (CheckBox)item.FindControl("SelectCheckBox"); // If the item is selected, display the appropriate message and // increment the count of selected items. if (selection != null) { if (selection.Checked) { Message.Text += "- " + item.Cells[1].Text + "<br />"; count++; } } } </script> <head runat="server"> <title>DataGrid Example</title> </head> <body> <form id="form1" runat="server"> <h3>DataGrid Example</h3> <b>Product List</b> <asp:DataGrid id="ItemsGrid" BorderColor="black" BorderWidth="1" CellPadding="3" AutoGenerateColumns="False" runat="server"> <HeaderStyle BackColor="#00aaaa"> </HeaderStyle> <Columns> <asp:BoundColumn DataField="IntegerValue" HeaderText="Item"/> <asp:BoundColumn DataField="StringValue" HeaderText="Description"/> <asp:BoundColumn DataField="CurrencyValue" HeaderText="Price" DataFormatString="{0:c}"> <ItemStyle HorizontalAlign="Right"> </ItemStyle> </asp:BoundColumn> <asp:TemplateColumn HeaderText="Select Item"> <ItemTemplate> <asp:CheckBox id="SelectCheckBox" Text="Add to Cart" Checked="False" runat="server"/> </ItemTemplate> </asp:TemplateColumn> </Columns> </asp:DataGrid> <br /><br /> <asp:Button id="SubmitButton" Text="Submit" OnClick = "Button_Click" runat="server"/> <br /><br /> <asp:Label id="Message" runat="server"/> </form> </body> </html>
- AspNetHostingPermission
호스팅된 환경에서 작업하는 데 필요한 권한입니다. 요청 값: LinkDemand, 권한 값: Minimal
- AspNetHostingPermission
호스팅된 환경에서 작업하는 데 필요한 권한입니다. 요청 값: InheritanceDemand, 권한 값: Minimal
System.Web.UI.Control
System.Web.UI.WebControls.WebControl
System.Web.UI.WebControls.BaseDataList
System.Web.UI.WebControls.DataGrid
Windows Vista, Windows XP SP2, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP Starter Edition, Windows Server 2003, Windows Server 2000 SP4, Windows Millennium Edition, Windows 98
.NET Framework 및 .NET Compact Framework에서 모든 플랫폼의 전체 버전을 지원하지는 않습니다. 지원되는 버전의 목록을 보려면 .NET Framework 시스템 요구 사항을 참조하십시오.
참고: