方法 : ユーザーが DataList Web サーバー コントロール内の項目を編集できるようにする

更新 : 2007 年 11 月

DataList Web サーバー コントロールの個別の項目をユーザーが編集できるようにすることができます。各項目が編集モードに設定されている場合、通常、変更できる値はテキスト ボックスに、またはユーザーが変更できるその他のコントロールに表示されます。

DataList コントロールの項目のユーザーによる編集を許可するには

  1. DataList コントロールの DataKeyField プロパティに、主キーを格納するデータのフィールド名を設定します。

  2. ItemTemplate (および、使用している場合は AlternatingItemTemplate) を作成し、これに Button Web サーバー コントロールを追加します。このボタンの CommandName プロパティを edit に設定します。

    90xwe9s3.alert_note(ja-jp,VS.90).gifメモ :

    Button Web サーバー コントロールを必要とする手順では、LinkButton または ImageButton コントロールを使用できます。

  3. 次のようなコントロールを含む DataList コントロールの EditItemTemplate を作成します。

    • ユーザーが変更できる値すべてに対するコントロール。たとえば、すべての文字データおよび数値データ用の TextBox コントロールを含めます。次の例に示すように、宣言 Eval メソッドを使用して、各コントロールのバインド先のフィールドを指定します。

      90xwe9s3.alert_security(ja-jp,VS.90).gifセキュリティに関するメモ :

      この例には、ユーザー入力を受け付けるテキスト ボックスがあるため、セキュリティ上の脅威になる可能性があります。既定では、ASP.NET Web ページは、ユーザー入力にスクリプトまたは HTML 要素が含まれていないことを検証します。詳細については、「スクリプトによる攻略の概要」を参照してください。

      <asp:TextBox ID="TextBox1" 
        runat="server" 
        Text='<%# Eval("ProductName") %>' />
      
    • Text プロパティを "Update" に設定し、CommandName プロパティを update (大文字と小文字を区別) に設定した Button コントロール。

    • Text プロパティを "Cancel" に設定し、CommandName プロパティを cancel に設定した Button コントロール。

      [Update] ボタンは、ユーザーが編集作業を終えて変更を保存する場合に使用します。[Cancel] ボタンは、ユーザーが変更を保存せずに編集を終了する場合に使用します。

  4. 次のタスクを実行するコードを記述します。

    • 編集モードに入るために DataList コントロールの EditItemIndex プロパティを項目のインデックス値に設定する、DataList コントロールの EditCommand イベントを処理します。ユーザーがクリックした項目のインデックスは、Item オブジェクトの ItemIndex プロパティから取得できます。次に、コントロールの DataBind メソッドを呼び出します。

    • DataList コントロールの EditItemIndex プロパティを -1 に設定してからコントロールの DataBind メソッドを呼び出す、DataList コントロールの CancelCommand イベントを処理します。

    • DataList コントロールの UpdateCommand イベントを処理します。このコードでは、現在の項目のコントロールから値を抽出し、これらを更新操作のためにデータ ソース コントロールに渡します。実際に使用するコードは、操作するデータ ソース コントロールの種類によって異なります。

使用例

DataList コントロールと SqlDataSource コントロールを使用して Northwind データベースの Categories テーブルの情報を表示する ASP.NET ページのコード例を次に示します。ユーザーは項目を編集できます。

90xwe9s3.alert_security(ja-jp,VS.90).gifセキュリティに関するメモ :

この例には、ユーザー入力を受け付けるテキスト ボックスがあるため、セキュリティ上の脅威になる可能性があります。既定では、ASP.NET Web ページは、ユーザー入力にスクリプトまたは HTML 要素が含まれていないことを検証します。詳細については、「スクリプトによる攻略の概要」を参照してください。

<%@ Page Language="VB" %>

<script runat="server">
Protected Sub DataList1_EditCommand(ByVal source As Object, _
        ByVal e As System.Web.UI.WebControls.DataListCommandEventArgs)
    DataList1.EditItemIndex = e.Item.ItemIndex
    DataList1.DataBind()
End Sub

Protected Sub DataList1_CancelCommand(ByVal source As Object, _
        ByVal e As System.Web.UI.WebControls.DataListCommandEventArgs)
    DataList1.EditItemIndex = -1
    DataList1.DataBind()
End Sub

Protected Sub DataList1_UpdateCommand(ByVal source As Object, _
        ByVal e As System.Web.UI.WebControls.DataListCommandEventArgs)
    Dim categoryID As String = _
        DataList1.DataKeys(e.Item.ItemIndex).ToString()
    Dim categoryName As TextBox = _
        CType(e.Item.FindControl("textCategoryName"), TextBox)
    Dim description As TextBox = _
        CType(e.Item.FindControl("textDescription"), TextBox)

    SqlDataSource1.UpdateParameters("original_CategoryID"). _
        DefaultValue = categoryID
    SqlDataSource1.UpdateParameters("categoryName"). _
        DefaultValue = categoryName.Text
    SqlDataSource1.UpdateParameters("Description"). _
        DefaultValue = description.Text
    SqlDataSource1.Update()
    DataList1.EditItemIndex = -1
    DataList1.DataBind()
End Sub
</script>

<html>
<head runat="server"></head>
<body>
  <form id="form1" runat="server">
    <div>
        <br />
        <asp:DataList runat="server" 
            DataKeyField="CategoryID" 
            DataSourceID="SqlDataSource1" ID="DataList1"
            OnEditCommand="DataList1_EditCommand" 
            OnCancelCommand="DataList1_CancelCommand" 
            OnUpdateCommand="DataList1_UpdateCommand">
            <EditItemTemplate>
                ID: <asp:Label ID="Label1" runat="server" 
                         Text='<%# Eval("CategoryID") %>'>
                    </asp:Label>
                <br />
                Name: <asp:TextBox ID="textCategoryName" runat="server" 
                         Text='<%# Eval("CategoryName") %>'>
                      </asp:TextBox>
                <br />
                Description: <asp:TextBox ID="textDescription" 
                                 runat="server" 
                        Text='<%# Eval("Description") %>'>
                     </asp:TextBox>
                <br />
                <asp:LinkButton ID="LinkButton1" runat="server" 
                    CommandName="update" >
                    Save
                </asp:LinkButton>
                &nbsp;
                <asp:LinkButton ID="LinkButton2" runat="server">
                    CommandName="cancel" 
                    Cancel
                </asp:LinkButton>
            </EditItemTemplate>
            <ItemTemplate>
                CategoryID:
                <asp:Label ID="CategoryIDLabel" runat="server" 
                    Text='<%# Eval("CategoryID") %>'>
                </asp:Label>
                <br />
                CategoryName:
                <asp:Label ID="CategoryNameLabel" runat="server"
                     Text='<%# Eval("CategoryName") %>'>
                </asp:Label>
                <br />
                Description:
                <asp:Label ID="DescriptionLabel" runat="server" 
                    Text='<%# Eval("Description") %>'>
                </asp:Label>
                <br />
                <asp:LinkButton runat="server" ID="LinkButton1" 
                    CommandName="edit" >
                    Edit
                </asp:LinkButton><br />
            </ItemTemplate>
        </asp:DataList>

        <asp:SqlDataSource ID="SqlDataSource1" runat="server" 
              ConnectionString=
                  "<%$ ConnectionStrings:NorthwindConnectionString %>"
            SelectCommand="SELECT [CategoryID], [CategoryName], 
                 [Description] FROM [Categories]"
            UpdateCommand="UPDATE [Categories] SET [CategoryName] = 
                 @CategoryName, [Description] = @Description 
                 WHERE [CategoryID] = @original_CategoryID">
            <UpdateParameters>
              <asp:Parameter Name="CategoryName" Type="String" />
              <asp:Parameter Name="Description" Type="String" />
              <asp:Parameter Name="original_CategoryID" Type="Int32" />
            </UpdateParameters>
        </asp:SqlDataSource>
    </div>
  </form>
</body>
</html>
<%@ Page Language="C#" %>
<script runat="server">
protected void DataList1_EditCommand(object source, 
    DataListCommandEventArgs e)
{
    DataList1.EditItemIndex = e.Item.ItemIndex;
    DataList1.DataBind();
}

protected void DataList1_CancelCommand(object source, 
    DataListCommandEventArgs e)
{
    DataList1.EditItemIndex = -1;
    DataList1.DataBind();
}

protected void DataList1_UpdateCommand(object source, 
    DataListCommandEventArgs e)
{
    String categoryID = 
         DataList1.DataKeys[e.Item.ItemIndex].ToString();
    String categoryName = 
         ((TextBox)e.Item.FindControl("textCategoryName")).Text;
    String description = 
         ((TextBox) e.Item.FindControl("textDescription")).Text;

    SqlDataSource1.UpdateParameters["original_CategoryID"].DefaultValue 
        = categoryID;
    SqlDataSource1.UpdateParameters["categoryName"].DefaultValue 
        = categoryName;
    SqlDataSource1.UpdateParameters["Description"].DefaultValue 
        = description;
    SqlDataSource1.Update();

    DataList1.EditItemIndex = -1;
    DataList1.DataBind();
}
</script>
<html>
<head runat="server"></head>
<body>
  <form id="form1" runat="server">
    <div>
        <br />
        <asp:DataList runat="server" 
            DataKeyField="CategoryID" 
            DataSourceID="SqlDataSource1" ID="DataList1"
            OnEditCommand="DataList1_EditCommand" 
            OnCancelCommand="DataList1_CancelCommand" 
            OnUpdateCommand="DataList1_UpdateCommand">
            <EditItemTemplate>
                ID: <asp:Label ID="Label1" runat="server" 
                         Text='<%# Eval("CategoryID") %>'>
                    </asp:Label>
                <br />
                Name: <asp:TextBox ID="textCategoryName" runat="server" 
                         Text='<%# Eval("CategoryName") %>'>
                      </asp:TextBox>
                <br />
                Description: <asp:TextBox ID="textDescription" 
                                 runat="server" 
                        Text='<%# Eval("Description") %>'>
                     </asp:TextBox>
                <br />
                <asp:LinkButton ID="LinkButton1" runat="server" 
                    CommandName="update" >
                    Save
                </asp:LinkButton>
                &nbsp;
                <asp:LinkButton ID="LinkButton2" runat="server">
                    CommandName="cancel" 
                    Cancel
                </asp:LinkButton>
            </EditItemTemplate>
            <ItemTemplate>
                CategoryID:
                <asp:Label ID="CategoryIDLabel" runat="server" 
                    Text='<%# Eval("CategoryID") %>'>
                </asp:Label>
                <br />
                CategoryName:
                <asp:Label ID="CategoryNameLabel" runat="server"
                     Text='<%# Eval("CategoryName") %>'>
                </asp:Label>
                <br />
                Description:
                <asp:Label ID="DescriptionLabel" runat="server" 
                    Text='<%# Eval("Description") %>'>
                </asp:Label>
                <br />
                <asp:LinkButton runat="server" ID="LinkButton1" 
                    CommandName="edit" >
                    Edit
                </asp:LinkButton><br />
            </ItemTemplate>
        </asp:DataList>

        <asp:SqlDataSource ID="SqlDataSource1" runat="server" 
              ConnectionString=
                 "<%$ ConnectionStrings:NorthwindConnectionString %>"
            SelectCommand="SELECT [CategoryID], [CategoryName], 
                 [Description] FROM [Categories]"
            UpdateCommand="UPDATE [Categories] SET [CategoryName] = 
                 @CategoryName, [Description] = @Description 
                 WHERE [CategoryID] = @original_CategoryID">
            <UpdateParameters>
               <asp:Parameter Name="CategoryName" Type="String" />
              <asp:Parameter Name="Description" Type="String" />
              <asp:Parameter Name="original_CategoryID" Type="Int32" />
            </UpdateParameters>
        </asp:SqlDataSource>
    </div>
  </form>
</body>
</html>

データを更新するには、更新するレコードの主キーが必要です。この値は、キーの配列を含む DataKeyField プロパティから取得できます。

項目の特定のコントロールの値を取得するには、Item イベント引数オブジェクトの FindControl メソッドを使用します。

SqlDataSource1.UpdateParameters ディクショナリに設定した値は、UpdateParameters 要素に設定した名前と一致する必要があります。

コードのコンパイル方法

このコードには、NorthwindConnectionString という名前の接続文字列が必要です。接続先のデータベースには、CategoryID、CategoryName、および Description というフィールドを持つ Categories というテーブルがあることが前提になっています。

ページがデータベースに接続するときに使用するアカウントには、Category テーブルを更新するアクセス許可が必要です。

堅牢性の高いプログラム

稼動環境では次のタスクを通常実行しますが、この例に示すコードでは実行しません。

  • このコードには、FindControl メソッドが有効なコントロールを返していることを確認するためのエラー チェックは含まれません。信頼性の高いコードにするには、FindControl メソッドによって返される値が null 参照 (Visual Basic では Nothing) ではないことを確認してください。

  • このコードでは、更新が正常に行われたかどうかはチェックされません。

セキュリティ

Web フォーム ページのユーザー入力には、悪意のあるクライアントのスクリプトが含まれる可能性があります。既定では、Web フォーム ページは、ユーザー入力にスクリプトまたは HTML 要素が含まれていないことを検証します。詳細については、「スクリプトによる攻略の概要」を参照してください。

参照

概念

SqlDataSource コントロールによるデータの変更

SqlDataSource コントロールにおけるパラメータの使用

参照

DataList Web サーバー コントロールの概要