共用方式為


EditCommandColumn 類別

定義

DataGrid 控制項的特殊資料行類型,其中包含 Edit 按鈕來編輯每個資料列中的資料項目。

public ref class EditCommandColumn : System::Web::UI::WebControls::DataGridColumn
public class EditCommandColumn : System.Web.UI.WebControls.DataGridColumn
type EditCommandColumn = class
    inherit DataGridColumn
Public Class EditCommandColumn
Inherits DataGridColumn
繼承
EditCommandColumn

範例

下列程式代碼範例示範如何將 物件新增 EditCommandColumnDataGrid 控件。


<%@ 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">
 
      // The Cart and CartView objects temporarily store the data source
      // for the DataGrid control while the page is being processed.
      DataTable Cart = new DataTable();
      DataView CartView;   
 
      void Page_Load(Object sender, EventArgs e) 
      {
 
         // With a database, use an select query to retrieve the data. Because 
         // the data source in this example is an in-memory DataTable, retrieve
         // the data from session state if it exists; otherwise, create the data
         // source.
         GetSource();

         // The DataGrid control maintains state between posts to the server;
         // it only needs to be bound to a data source the first time the page
         // is loaded or when the data source is updated.
         if (!IsPostBack)
         {

            BindGrid();

         }
                   
      }
 
      void ItemsGrid_Edit(Object sender, DataGridCommandEventArgs e) 
      {

         // Set the EditItemIndex property to the index of the item clicked 
         // in the DataGrid control to enable editing for that item. Be sure
         // to rebind the DateGrid to the data source to refresh the control.
         ItemsGrid.EditItemIndex = e.Item.ItemIndex;
         BindGrid();

      }
 
      void ItemsGrid_Cancel(Object sender, DataGridCommandEventArgs e) 
      {

         // Set the EditItemIndex property to -1 to exit editing mode. 
         // Be sure to rebind the DateGrid to the data source to refresh
         // the control.
         ItemsGrid.EditItemIndex = -1;
         BindGrid();

      }
 
      void ItemsGrid_Update(Object sender, DataGridCommandEventArgs e) 
      {

         // Retrieve the text boxes that contain the values to update.
         // For bound columns, the edited value is stored in a TextBox.
         // The TextBox is the 0th control in a cell's Controls collection.
         // Each cell in the Cells collection of a DataGrid item represents
         // a column in the DataGrid control.
         TextBox qtyText = (TextBox)e.Item.Cells[3].Controls[0];
         TextBox priceText = (TextBox)e.Item.Cells[4].Controls[0];
 
         // Retrieve the updated values.
         String item = e.Item.Cells[2].Text;
         String qty = qtyText.Text;
         String price = priceText.Text;
        
         DataRow dr;
 
         // With a database, use an update command to update the data. 
         // Because the data source in this example is an in-memory 
         // DataTable, delete the old row and replace it with a new one.
 
         // Remove the old entry and clear the row filter.
         CartView.RowFilter = "Item='" + item + "'";
         if (CartView.Count > 0)
         {
            CartView.Delete(0);
         }
         CartView.RowFilter = "";
 
         // ***************************************************************
         // Insert data validation code here. Be sure to validate the
         // values entered by the user before converting to the appropriate
         // data types and updating the data source.
         // ***************************************************************

         // Add the new entry.
         dr = Cart.NewRow();
         dr[0] = Convert.ToInt32(qty);
         dr[1] = item;

         // If necessary, remove the '$' character from the price before 
         // converting it to a Double.
         if(price[0] == '$')
         {
            dr[2] = Convert.ToDouble(price.Substring(1));
         }
         else
         {
            dr[2] = Convert.ToDouble(price);
         }

         Cart.Rows.Add(dr);
 
         // Set the EditItemIndex property to -1 to exit editing mode. 
         // Be sure to rebind the DateGrid to the data source to refresh
         // the control.
         ItemsGrid.EditItemIndex = -1;
         BindGrid();

      }
 
      void BindGrid() 
      {

         // Set the data source and bind to the Data Grid control.
         ItemsGrid.DataSource = CartView;
         ItemsGrid.DataBind();

      }

      void GetSource()
      {

         // For this example, the data source is a DataTable that is stored
         // in session state. If the data source does not exist, create it;
         //  otherwise, load the data.
         if (Session["ShoppingCart"] == null) 
         {     

            // Create the sample data.
            DataRow dr;  
 
            // Define the columns of the table.
            Cart.Columns.Add(new DataColumn("Qty", typeof(Int32)));
            Cart.Columns.Add(new DataColumn("Item", typeof(String)));
            Cart.Columns.Add(new DataColumn("Price", typeof(Double)));

            // Store the table in session state to persist its values 
            // between posts to the server.
            Session["ShoppingCart"] = Cart;
             
            // Populate the DataTable with sample data.
            for (int i = 1; i <= 9; i++) 
            {
               dr = Cart.NewRow();
               if (i % 2 != 0)
               {
                  dr[0] = 2;
               }
               else
               {
                  dr[0] = 1;
               }
               dr[1] = "Item " + i.ToString();
               dr[2] = (1.23 * (i + 1));
               Cart.Rows.Add(dr);
            }

         } 

         else
         {

            // Retrieve the sample data from session state.
            Cart = (DataTable)Session["ShoppingCart"];

         }         
 
         // Create a DataView and specify the field to sort by.
         CartView = new DataView(Cart);
         CartView.Sort="Item";

         return;

      }

      void ItemsGrid_Command(Object sender, DataGridCommandEventArgs e)
      {

         switch(((LinkButton)e.CommandSource).CommandName)
         {

            case "Delete":
               DeleteItem(e);
               break;

            // Add other cases here, if there are multiple ButtonColumns in 
            // the DataGrid control.

            default:
               // Do nothing.
               break;

         }

      }

      void DeleteItem(DataGridCommandEventArgs e)
      {

         // e.Item is the table row where the command is raised. For bound
         // columns, the value is stored in the Text property of a TableCell.
         TableCell itemCell = e.Item.Cells[2];
         string item = itemCell.Text;

         // Remove the selected item from the data source.         
         CartView.RowFilter = "Item='" + item + "'";
         if (CartView.Count > 0) 
         {     
            CartView.Delete(0);
         }
         CartView.RowFilter = "";

         // Rebind the data source to refresh the DataGrid control.
         BindGrid();

      }
 
   </script>
 
<head runat="server">
    <title>DataGrid Editing Example</title>
</head>
<body>
 
   <form id="form1" runat="server">

      <h3>DataGrid Editing Example</h3>
 
      <asp:DataGrid id="ItemsGrid"
           BorderColor="black"
           BorderWidth="1"
           CellPadding="3"
           OnEditCommand="ItemsGrid_Edit"
           OnCancelCommand="ItemsGrid_Cancel"
           OnUpdateCommand="ItemsGrid_Update"
           OnItemCommand="ItemsGrid_Command"
           AutoGenerateColumns="false"
           runat="server">

         <HeaderStyle BackColor="#aaaadd">
         </HeaderStyle>
 
         <Columns>

            <asp:EditCommandColumn
                 EditText="Edit"
                 CancelText="Cancel"
                 UpdateText="Update" 
                 HeaderText="Edit item">

               <ItemStyle Wrap="False">
               </ItemStyle>

               <HeaderStyle Wrap="False">
               </HeaderStyle>

            </asp:EditCommandColumn>

            <asp:ButtonColumn 
                 HeaderText="Delete item" 
                 ButtonType="LinkButton" 
                 Text="Delete" 
                 CommandName="Delete"/>  
 
            <asp:BoundColumn HeaderText="Item" 
                 ReadOnly="True" 
                 DataField="Item"/>
 
            <asp:BoundColumn HeaderText="Quantity" 
                 DataField="Qty"/>
 
            <asp:BoundColumn HeaderText="Price"
                 DataField="Price"
                 DataFormatString="{0:c}"/>
 
         </Columns>
 
      </asp:DataGrid>

   </form>
 
</body>
</html>

<%@ Page Language="VB" 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">
 
      ' The Cart and CartView objects temporarily store the data source
      ' for the DataGrid control while the page is being processed.
      Dim Cart As DataTable = New DataTable()
      Dim CartView As DataView    
 
      Sub Page_Load(sender As Object, e As EventArgs) 
 
         ' With a database, use an select query to retrieve the data. Because 
         ' the data source in this example is an in-memory DataTable, retrieve
         ' the data from session state if it exists; otherwise create the data
         ' source.
         GetSource()

         ' The DataGrid control maintains state between posts to the server;
         ' it only needs to be bound to a data source the first time the page
         ' is loaded or when the data source is updated.
         If Not IsPostBack Then

            BindGrid()

         End If
                   
      End Sub
 
      Sub ItemsGrid_Edit(sender As Object, e As DataGridCommandEventArgs) 

         ' Set the EditItemIndex property to the index of the item clicked 
         ' in the DataGrid control to enable editing for that item. Be sure
         ' to rebind the DateGrid to the data source to refresh the control.
         ItemsGrid.EditItemIndex = e.Item.ItemIndex
         BindGrid()

      End Sub
 
      Sub ItemsGrid_Cancel(sender As Object, e As DataGridCommandEventArgs) 

         ' Set the EditItemIndex property to -1 to exit editing mode.
         ' Be sure to rebind the DateGrid to the data source to refresh
         ' the control.
         ItemsGrid.EditItemIndex = -1
         BindGrid()

      End Sub
 
      Sub ItemsGrid_Update(sender As Object, e As DataGridCommandEventArgs) 

         ' Retrieve the text boxes that contain the values to update.
         ' For bound columns, the edited value is stored in a TextBox.
         ' The TextBox is the 0th control in a cell's Controls collection.
         ' Each cell in the Cells collection of a DataGrid item represents
         ' a column in the DataGrid control.
         Dim qtyText As TextBox = CType(e.Item.Cells(3).Controls(0), TextBox)
         Dim priceText As TextBox = CType(e.Item.Cells(4).Controls(0), TextBox)
 
         ' Retrieve the updated values.
         Dim item As String = e.Item.Cells(2).Text
         Dim qty As String = qtyText.Text
         Dim price As String = priceText.Text
        
         Dim dr As DataRow
 
         ' With a database, use an update command to update the data. 
         ' Because the data source in this example is an in-memory 
         ' DataTable, delete the old row and replace it with a new one.
 
         ' Remove the old entry and clear the row filter.
         CartView.RowFilter = "Item='" & item & "'"
         If CartView.Count > 0 Then
       
            CartView.Delete(0)
         
         End If 
         CartView.RowFilter = ""
 
         ' ***************************************************************
         ' Insert data validation code here. Be sure to validate the
         ' values entered by the user before converting to the appropriate
         ' data types and updating the data source.
         ' ***************************************************************

         ' Add the new entry.
         dr = Cart.NewRow()
         dr(0) = Convert.ToInt32(qty)
         dr(1) = item

         ' If necessary, remove the '$' character from the price before 
         ' converting it to a Double.
         If price.Chars(0) = "$" Then
         
            dr(2) = Convert.ToDouble(price.Substring(1))
         
         Else
         
            dr(2) = Convert.ToDouble(price)
         
         End If

         Cart.Rows.Add(dr)
 
         ' Set the EditItemIndex property to -1 to exit editing mode.
         ' Be sure to rebind the DateGrid to the data source to refresh
         ' the control.
         ItemsGrid.EditItemIndex = -1
         BindGrid()

      End Sub
 
      Sub BindGrid() 

         ' Set the data source and bind to the Data Grid control.
         ItemsGrid.DataSource = CartView
         ItemsGrid.DataBind()

      End Sub

      Sub GetSource()

         ' For this example, the data source is a DataTable that is stored
         ' in session state. If the data source does not exist, create it;
         ' otherwise, load the data.
         If Session("ShoppingCart") Is Nothing Then 

            ' Create the sample data.
            Dim dr As DataRow  
 
            ' Define the columns of the table.
            Cart.Columns.Add(new DataColumn("Qty", GetType(Int32)))
            Cart.Columns.Add(new DataColumn("Item", GetType(String)))
            Cart.Columns.Add(new DataColumn("Price", GetType(Double)))

            ' Store the table in session state to persist its values
            ' between posts to the server.
            Session("ShoppingCart") = Cart
             
            ' Populate the DataTable with sample data.
            Dim i As Integer

            For i = 1 To 9 
            
               dr = Cart.NewRow()
               If (i Mod 2) <> 0 Then

                  dr(0) = 2
               
               Else
               
                  dr(0) = 1
               
               End If

               dr(1) = "Item " & i.ToString()
               dr(2) = (1.23 * (i + 1))
               Cart.Rows.Add(dr)
            
            Next i

         Else

            ' Retrieve the sample data from session state.
            Cart = CType(Session("ShoppingCart"), DataTable)

         End If         
 
         ' Create a DataView and specify the field to sort by.
         CartView = New DataView(Cart)
         CartView.Sort="Item"

         Return

      End Sub

      Sub ItemsGrid_Command(sender As Object, e As DataGridCommandEventArgs)

         Select (CType(e.CommandSource, LinkButton)).CommandName

            Case "Delete"
               DeleteItem(e)

            ' Add other cases here, if there are multiple ButtonColumns in 
            ' the DataGrid control.

            Case Else
               ' Do nothing.

         End Select

      End Sub

      Sub DeleteItem(e As DataGridCommandEventArgs)

         ' e.Item is the table row where the command is raised. For bound 
         ' columns, the value is stored in the Text property of a TableCell.
         Dim itemCell As TableCell = e.Item.Cells(2)
         Dim item As String = itemCell.Text

         ' Remove the selected item from the data source.         
         CartView.RowFilter = "Item='" & item + "'"
         If CartView.Count > 0 Then 
              
            CartView.Delete(0)

         End If
         
         CartView.RowFilter = ""

         ' Rebind the data source to refresh the DataGrid control.
         BindGrid()

      End Sub
 
   </script>
 
<head runat="server">
    <title>DataGrid Editing Example</title>
</head>
<body>
 
   <form id="form1" runat="server">

      <h3>DataGrid Editing Example</h3>
 
      <asp:DataGrid id="ItemsGrid"
           BorderColor="black"
           BorderWidth="1"
           CellPadding="3"
           OnEditCommand="ItemsGrid_Edit"
           OnCancelCommand="ItemsGrid_Cancel"
           OnUpdateCommand="ItemsGrid_Update"
           OnItemCommand="ItemsGrid_Command"
           AutoGenerateColumns="false"
           runat="server">

         <HeaderStyle BackColor="#aaaadd">
         </HeaderStyle>
 
         <Columns>

            <asp:EditCommandColumn
                 EditText="Edit"
                 CancelText="Cancel"
                 UpdateText="Update" 
                 HeaderText="Edit item">

               <ItemStyle Wrap="False">
               </ItemStyle>

               <HeaderStyle Wrap="False">
               </HeaderStyle>

            </asp:EditCommandColumn>

            <asp:ButtonColumn 
                 HeaderText="Delete item" 
                 ButtonType="LinkButton" 
                 Text="Delete" 
                 CommandName="Delete"/>  
 
            <asp:BoundColumn HeaderText="Item" 
                 ReadOnly="True" 
                 DataField="Item"/>
 
            <asp:BoundColumn HeaderText="Quantity" 
                 DataField="Qty"/>
 
            <asp:BoundColumn HeaderText="Price"
                 DataField="Price"
                 DataFormatString="{0:c}"/>
 
         </Columns>
 
      </asp:DataGrid>

   </form>
 
</body>
</html>

備註

使用 類別 EditCommandColumn 為控制項建立特殊資料行 DataGrid ,其中包含方格中每個數據列的 EditUpdateCancel 按鈕。 這些按鈕可讓您編輯控制項中 DataGrid 數據列的值。

如果未選取任何數據列, Edit 控制項中每個資料列的 EditCommandColumn 按鈕會顯示在物件中 DataGridEdit按兩下項目按鈕時,會引發事件,EditCommand並將Edit按鈕取代為 UpdateCancel 按鈕。 您必須提供程式碼來處理 EditCommand 事件。 典型的事件處理程式會將 EditItemIndex 屬性設定為選取的數據列,然後將數據重新系結至 DataGrid 控件。

注意

您必須提供、 EditTextUpdateText 屬性的值CancelText。 否則,相關聯的按鈕不會出現在 中 EditCommandColumn

中的 EditCommandColumn 按鈕可以藉由設定 ButtonType 屬性,設定為超連結或按鈕來顯示。

Update按兩下或 Cancel 按鈕會分別引發 UpdateCommandCancelCommand 事件。 您必須提供程式碼來處理這些事件。

事件的一般處理程式 UpdateCommand 會更新數據、將 屬性設定 EditItemIndex-1 (取消選取專案) ,然後將數據重新系結至 DataGrid 控件。

事件的一般處理程式 CancelCommand 會將 EditItemIndex 屬性設定為 -1 (以取消選取專案) ,然後將數據重新系結至 DataGrid 控件。

警告

對象 EditCommandColumn 可用來顯示使用者輸入,其中可能包含惡意用戶端腳本。 檢查從用戶端傳送的任何資訊,以取得可執行腳本、SQL 語句或其他程式代碼,再將其顯示在應用程式中。 您可以使用驗證控制項來驗證使用者輸入,再顯示控制項中的 DataGrid 輸入文字。 ASP.NET 提供輸入要求驗證功能,以封鎖使用者輸入中的腳本和 HTML。 如需詳細資訊,請參閱 保護標準控件如何:藉由將 HTML 編碼套用至字串來保護 Web 應用程式中的腳本惡意探索,以及 驗證 ASP.NET 網頁中的使用者輸入

根據預設,按兩下控制件中的EditCommandColumn按鈕時Update,就會執行頁面驗證。 頁面驗證會判斷頁面上與驗證控件相關聯的輸入控件是否通過驗證控件所指定的驗證規則。 若要防止頁面驗證發生,請將 CausesValidation 屬性設定為 false

建構函式

EditCommandColumn()

初始化 EditCommandColumn 類別的新執行個體。

屬性

ButtonType

取得或設定資料行的按鈕類型。

CancelText

取得或設定要顯示於 EditCommandColumnCancel 命令按鈕的文字。

CausesValidation

取得或設定值,表示按一下 EditCommandColumn 物件中的 [Update] 按鈕時,是否執行驗證。

DesignMode

取得值,指出資料行是否處在設計模式中。

(繼承來源 DataGridColumn)
EditText

取得或設定要顯示於 EditCommandColumn 中 [Edit] 按鈕的文字。

FooterStyle

取得資料行行尾區段的樣式屬性。

(繼承來源 DataGridColumn)
FooterText

取得或設定顯示於資料行行尾區段的文字。

(繼承來源 DataGridColumn)
HeaderImageUrl

取得或設定要顯示於資料行行首區段的影像位置。

(繼承來源 DataGridColumn)
HeaderStyle

取得資料行行首區段的樣式屬性。

(繼承來源 DataGridColumn)
HeaderText

取得或設定顯示於資料行行首區段的文字。

(繼承來源 DataGridColumn)
IsTrackingViewState

取得值,判斷是否標記 DataGridColumn 物件以儲存其狀態。

(繼承來源 DataGridColumn)
ItemStyle

取得資料行項目儲存格的樣式屬性。

(繼承來源 DataGridColumn)
Owner

取得有資料行做為其中成員的 DataGrid 控制項。

(繼承來源 DataGridColumn)
SortExpression

在選取資料行來排序時,取得或設定欄位或運算式的名稱以傳遞至 OnSortCommand(DataGridSortCommandEventArgs) 方法。

(繼承來源 DataGridColumn)
UpdateText

取得或設定要顯示於 EditCommandColumnUpdate 命令按鈕的文字。

ValidationGroup

取得或設定驗證控制項群組,EditCommandColumn 物件會在回傳至伺服器時,針對這個群組進行驗證。

ViewState

取得 StateBag 物件,該物件允許衍生自 DataGridColumn 類別的資料行儲存其屬性。

(繼承來源 DataGridColumn)
Visible

取得或設定值,指出資料行是否可見於 DataGrid 控制項中。

(繼承來源 DataGridColumn)

方法

Equals(Object)

判斷指定的物件是否等於目前的物件。

(繼承來源 Object)
GetHashCode()

做為預設雜湊函式。

(繼承來源 Object)
GetType()

取得目前執行個體的 Type

(繼承來源 Object)
Initialize()

提供基底實作,以將衍生自 DataGridColumn 類別的資料行重設為其初始狀態。

(繼承來源 DataGridColumn)
InitializeCell(TableCell, Int32, ListItemType)

初始化資料行中的儲存格。

LoadViewState(Object)

載入 DataGridColumn 物件的狀態。

(繼承來源 DataGridColumn)
MemberwiseClone()

建立目前 Object 的淺層複製。

(繼承來源 Object)
OnColumnChanged()

呼叫 OnColumnsChanged() 方法。

(繼承來源 DataGridColumn)
SaveViewState()

儲存 DataGridColumn 物件的目前狀態。

(繼承來源 DataGridColumn)
ToString()

傳回資料行的字串表示。

(繼承來源 DataGridColumn)
TrackViewState()

導致對伺服器控制項的檢視狀態變更的追蹤 (Tracking),以便它們能夠儲存於伺服器控制項的 StateBag 物件。

(繼承來源 DataGridColumn)

明確介面實作

IStateManager.IsTrackingViewState

取得值,指出資料行是否正在追蹤 (Tracking) 檢視狀態變更。

(繼承來源 DataGridColumn)
IStateManager.LoadViewState(Object)

載入先前儲存的狀態。

(繼承來源 DataGridColumn)
IStateManager.SaveViewState()

傳回包含狀態變更的物件。

(繼承來源 DataGridColumn)
IStateManager.TrackViewState()

啟動追蹤狀態的變更。

(繼承來源 DataGridColumn)

適用於

另請參閱