GridView.RowCommand 이벤트
정의
중요
일부 정보는 릴리스되기 전에 상당 부분 수정될 수 있는 시험판 제품과 관련이 있습니다. Microsoft는 여기에 제공된 정보에 대해 어떠한 명시적이거나 묵시적인 보증도 하지 않습니다.
컨트롤에서 단추를 클릭할 때 발생합니다 GridView .
public:
event System::Web::UI::WebControls::GridViewCommandEventHandler ^ RowCommand;
public event System.Web.UI.WebControls.GridViewCommandEventHandler RowCommand;
member this.RowCommand : System.Web.UI.WebControls.GridViewCommandEventHandler
Public Custom Event RowCommand As GridViewCommandEventHandler
이벤트 유형
예제
소스 코드가 있는 Visual Studio 웹 사이트 프로젝트는 다운로드 항목과 함께 사용할 수 있습니다.
다음 예제에서는 행의 추가 단추를 클릭할 때 컨트롤에서 GridView 컨트롤에 고객의 이름을 추가 하는 ListBox 이벤트를 사용 RowCommand 하는 방법을 보여 줍니다.
<%@ Page language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
void ContactsGridView_RowCommand(Object sender, GridViewCommandEventArgs e)
{
// If multiple buttons are used in a GridView control, use the
// CommandName property to determine which button was clicked.
if(e.CommandName=="Add")
{
// Convert the row index stored in the CommandArgument
// property to an Integer.
int index = Convert.ToInt32(e.CommandArgument);
// Retrieve the row that contains the button clicked
// by the user from the Rows collection.
GridViewRow row = ContactsGridView.Rows[index];
// Create a new ListItem object for the contact in the row.
ListItem item = new ListItem();
item.Text = Server.HtmlDecode(row.Cells[2].Text) + " " +
Server.HtmlDecode(row.Cells[3].Text);
// If the contact is not already in the ListBox, add the ListItem
// object to the Items collection of the ListBox control.
if (!ContactsListBox.Items.Contains(item))
{
ContactsListBox.Items.Add(item);
}
}
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>GridView RowCommand Example</title>
</head>
<body>
<form id="form1" runat="server">
<h3>GridView RowCommand Example</h3>
<table width="100%">
<tr>
<td style="width:50%">
<asp:gridview id="ContactsGridView"
datasourceid="ContactsSource"
allowpaging="true"
autogeneratecolumns="false"
onrowcommand="ContactsGridView_RowCommand"
runat="server">
<columns>
<asp:buttonfield buttontype="Link"
commandname="Add"
text="Add"/>
<asp:boundfield datafield="ContactID"
headertext="Contact ID"/>
<asp:boundfield datafield="FirstName"
headertext="First Name"/>
<asp:boundfield datafield="LastName"
headertext="Last Name"/>
</columns>
</asp:gridview>
</td>
<td style="vertical-align:top; width:50%">
Contacts: <br/>
<asp:listbox id="ContactsListBox"
runat="server" Height="200px" Width="200px"/>
</td>
</tr>
</table>
<!-- This example uses Microsoft SQL Server and connects -->
<!-- to the AdventureWorks sample database. Use an ASP.NET -->
<!-- expression to retrieve the connection string value -->
<!-- from the Web.config file. -->
<asp:sqldatasource id="ContactsSource"
selectcommand="Select [ContactID], [FirstName], [LastName] From Person.Contact"
connectionstring="<%$ ConnectionStrings:AdventureWorks_DataConnectionString%>"
runat="server"/>
</form>
</body>
</html>
<%@ Page language="VB" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
Sub ContactsGridView_RowCommand(ByVal sender As Object, ByVal e As GridViewCommandEventArgs)
' If multiple buttons are used in a GridView control, use the
' CommandName property to determine which button was clicked.
If e.CommandName = "Add" Then
' Convert the row index stored in the CommandArgument
' property to an Integer.
Dim index As Integer = Convert.ToInt32(e.CommandArgument)
' Retrieve the row that contains the button clicked
' by the user from the Rows collection.
Dim row As GridViewRow = ContactsGridView.Rows(index)
' Create a new ListItem object for the contact in the row.
Dim item As New ListItem()
item.Text = Server.HtmlDecode(row.Cells(2).Text) & " " & _
Server.HtmlDecode(row.Cells(3).Text)
' If the contact is not already in the ListBox, add the ListItem
' object to the Items collection of the ListBox control.
If Not ContactsListBox.Items.Contains(item) Then
ContactsListBox.Items.Add(item)
End If
End If
End Sub
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
<title>GridView RowCommand Example</title>
</head>
<body>
<form id="form1" runat="server">
<h3>GridView RowCommand Example</h3>
<table width="100%">
<tr>
<td style="width:50%">
<asp:gridview id="ContactsGridView"
datasourceid="ContactsSource"
allowpaging="true"
autogeneratecolumns="false"
onrowcommand="ContactsGridView_RowCommand"
runat="server">
<columns>
<asp:buttonfield buttontype="Link"
commandname="Add"
text="Add"/>
<asp:boundfield datafield="ContactID"
headertext="Contact ID"/>
<asp:boundfield datafield="FirstName"
headertext="First Name"/>
<asp:boundfield datafield="LastName"
headertext="Last Name"/>
</columns>
</asp:gridview>
</td>
<td style="vertical-align:top; width:50%">
Contacts: <br/>
<asp:listbox id="ContactsListBox"
runat="server" Height="200px" Width="200px"/>
</td>
</tr>
</table>
<!-- This example uses Microsoft SQL Server and connects -->
<!-- to the AdventureWorks sample database. Use an ASP.NET -->
<!-- expression to retrieve the connection string value -->
<!-- from the Web.config file. -->
<asp:sqldatasource id="ContactsSource"
selectcommand="Select [ContactID], [FirstName], [LastName] From Person.Contact"
connectionstring="<%$ ConnectionStrings:AdventureWorks_DataConnectionString%>"
runat="server"/>
</form>
</body>
</html>
다음 예제에서는 행 단추를 클릭할 때 이벤트를 사용하여 RowCommand 제품 가격을 업데이트하는 방법을 보여 줍니다. 이 예제에서는 컨트롤에 대해 GridView 페이징 기능을 사용하도록 설정하고 컨트롤의 Button 속성을 적절한 행 인덱스로 설정합니다CommandArgument.
<%@ Page language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
void ProductsGridView_RowCommand(Object sender, GridViewCommandEventArgs e)
{
// If multiple buttons are used in a GridView control, use the
// CommandName property to determine which button was clicked.
if(e.CommandName=="Increase")
{
// Convert the row index stored in the CommandArgument
// property to an Integer.
int index = Convert.ToInt32(e.CommandArgument);
// Retrieve the row that contains the button clicked
// by the user from the Rows collection.
GridViewRow row = ProductsGridView.Rows[index];
// Calculate the new price.
Label listPriceTextBox = (Label)row.FindControl("PriceLabel");
listPriceTextBox.Text = (Convert.ToDouble(listPriceTextBox.Text) * 1.05).ToString();
// Update the row.
ProductsGridView.UpdateRow(index, false);
}
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>GridView RowCommand Example</title>
</head>
<body>
<form id="form1" runat="server">
<h3>GridView RowCommand Example</h3>
<asp:GridView id="ProductsGridView"
DataSourceID="ProductsDataSource"
DataKeyNames="ProductID"
AllowPaging="True"
OnRowCommand="ProductsGridView_RowCommand"
AutoGenerateColumns="False"
runat="server">
<Columns>
<asp:BoundField DataField="Name" HeaderText="Product Name" />
<asp:BoundField DataField="ProductNumber" HeaderText="Product Number" />
<asp:TemplateField HeaderText="Price">
<ItemTemplate>
<asp:Label ID="PriceLabel" runat="server"
Text='<%# Bind("ListPrice") %>'>
</asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:Button runat="server" ID="IncreaseButton"
Text="Increase Price 5%"
CommandName="Increase"
CommandArgument="<%# ((GridViewRow) Container).RowIndex %>" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<!-- This example uses Microsoft SQL Server and connects -->
<!-- to the AdventureWorks sample database. Use an ASP.NET -->
<!-- expression to retrieve the connection string value -->
<!-- from the Web.config file. -->
<asp:SqlDataSource id="ProductsDataSource"
SelectCommand="SELECT [ProductID], [Name], [ProductNumber], [ListPrice]
FROM Production.Product
WHERE ListPrice <> 0"
UpdateCommand="UPDATE Production.Product SET [ListPrice] = @ListPrice
WHERE [ProductID] = @ProductID"
ConnectionString="<%$ ConnectionStrings:AdventureWorks_DataConnectionString %>"
runat="server" />
</form>
</body>
</html>
<%@ Page language="VB" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
Sub ProductsGridView_RowCommand(ByVal sender As Object, ByVal e As GridViewCommandEventArgs)
' If multiple buttons are used in a GridView control, use the
' CommandName property to determine which button was clicked.
If e.CommandName = "Increase" Then
' Convert the row index stored in the CommandArgument
' property to an Integer.
Dim index = Convert.ToInt32(e.CommandArgument)
' Retrieve the row that contains the button clicked
' by the user from the Rows collection.
Dim row = ProductsGridView.Rows(index)
' Calculate the new price.
Dim listPriceTextBox = CType(row.FindControl("PriceLabel"), Label)
listPriceTextBox.Text = (Convert.ToDouble(listPriceTextBox.Text) * 1.05).ToString()
' Update the row.
ProductsGridView.UpdateRow(index, False)
End If
End Sub
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>GridView RowCommand Example</title>
</head>
<body>
<form id="form1" runat="server">
<h3>GridView RowCommand Example</h3>
<asp:GridView id="ProductsGridView"
DataSourceID="ProductsDataSource"
DataKeyNames="ProductID"
AllowPaging="True"
OnRowCommand="ProductsGridView_RowCommand"
AutoGenerateColumns="False"
runat="server">
<Columns>
<asp:BoundField DataField="Name" HeaderText="Product Name" />
<asp:BoundField DataField="ProductNumber" HeaderText="Product Number" />
<asp:TemplateField HeaderText="Price">
<ItemTemplate>
<asp:Label ID="PriceLabel" runat="server"
Text='<%# Bind("ListPrice") %>'>
</asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:Button runat="server" ID="IncreaseButton"
Text="Increase Price 5%"
CommandName="Increase"
CommandArgument="<%# CType(Container, GridViewRow).RowIndex %>" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<!-- This example uses Microsoft SQL Server and connects -->
<!-- to the AdventureWorks sample database. Use an ASP.NET -->
<!-- expression to retrieve the connection string value -->
<!-- from the Web.config file. -->
<asp:SqlDataSource id="ProductsDataSource"
SelectCommand="SELECT [ProductID], [Name], [ProductNumber], [ListPrice]
FROM Production.Product
WHERE ListPrice <> 0"
UpdateCommand="UPDATE Production.Product SET [ListPrice] = @ListPrice
WHERE [ProductID] = @ProductID"
ConnectionString="<%$ ConnectionStrings:AdventureWorks_DataConnectionString %>"
runat="server" />
</form>
</body>
</html>
설명
컨트롤 RowCommand 에서 단추를 클릭하면 이벤트가 발생합니다 GridView . 이렇게 하면 이 이벤트가 발생할 때마다 사용자 지정 루틴을 수행하는 이벤트 처리 메서드를 제공할 수 있습니다.
컨트롤 내의 GridView 단추는 컨트롤의 기본 제공 기능 중 일부를 호출할 수도 있습니다. 이러한 작업 중 하나를 수행하려면 단추의 속성을 다음 표의 값 중 하나로 설정합니다 CommandName .
CommandName 값 |
설명 |
|---|---|
Cancel |
편집 작업을 취소하고 컨트롤을 GridView 읽기 전용 모드로 반환합니다. RowCancelingEdit 이벤트를 발생시킵니다. |
Delete |
현재 레코드를 삭제합니다. 및 RowDeleted 이벤트를 발생합니다RowDeleting. |
Edit |
현재 레코드를 편집 모드로 전환합니다. RowEditing 이벤트를 발생시킵니다. |
Page |
페이징 작업을 수행합니다.
CommandArgument 단추의 속성을 "First", "Last", "Next", "Prev" 또는 페이지 번호로 설정하여 수행할 페이징 작업의 유형을 지정합니다. 및 PageIndexChanged 이벤트를 발생합니다PageIndexChanging. |
Select |
현재 레코드를 선택합니다. 및 SelectedIndexChanged 이벤트를 발생합니다SelectedIndexChanging. |
Sort |
컨트롤을 정렬합니다 GridView . 및 Sorted 이벤트를 발생합니다Sorting. |
Update |
데이터 원본의 현재 레코드를 업데이트합니다. 및 RowUpdated 이벤트를 발생합니다RowUpdating. |
이전 표에 RowCommand 나열된 단추를 클릭할 때 이벤트가 발생하지만 테이블에 나열된 이벤트를 작업에 사용하는 것이 좋습니다.
GridViewCommandEventArgs 개체가 이벤트 처리 메서드에 전달되므로 클릭한 단추의 명령 이름과 명령 인수를 확인할 수 있습니다.
메모
이벤트를 발생시킨 행의 인덱스 확인 하려면 이벤트에 전달 되는 이벤트 인수의 속성을 사용 합니다 CommandArgument . 클래스는 ButtonField 적절한 인덱스 CommandArgument 값으로 속성을 자동으로 채웁니다. 다른 명령 단추의 경우 명령 단추의 CommandArgument 속성을 수동으로 설정해야 합니다. 예를 들어 컨트롤에 페이징을 CommandArgument<%# Container.DataItemIndex %> 사용할 수 없는 경우 GridView 를 설정할 수 있습니다.
이벤트를 처리하는 방법에 대한 자세한 내용은 이벤트 처리 및 발생을 참조하세요.