ASP.Net DataList Delete Command using C#

Updated on 08 Aug 2012,
Published on 14 Apr 2009

Delete Command of ASP.Net DataList Control provides you the functionality to permanently remove the record from the database. In this tutorial we will use C# code to delete the data item from database. Delete action will execute only when user will click the delete link button having the CommandName property value equal to delete. Here we will continue extending the DataList control C# code tutorial series to add the functionality of Delete command using link button. You can get the rest of the code for edit command, cancel command and update command from the previous tutorials of DataList. Following is the list of DataList Tutorials with C# code for:

1. DataList Edit command

2. DataList Cancel command

3. DataList Update command

HTML code for DataList Control having Delete Link

You can use the following HTML code snippet to display the delete button in your DataList control when it renders on ASP.Net web page. Following code snippet will provide you the complete HTML code template Control including OnEditCommand, OnCancelCommand, OnUpdateCommand and OnDeleteCommand.

<asp:DataList ID="DataList1" 
    runat="server" 
    DataKeyField="ProductID" 
    OnEditCommand="DataList1_EditCommand"
    OnCancelCommand="DataList1_CancelCommand" 
    OnUpdateCommand="DataList1_UpdateCommand"
    OnDeleteCommand="DataList1_DeleteCommand">
    <HeaderTemplate>
        <table>
            <tr>
                <th style="width: 250px">
                    Product Name
                </th>
                <th style="width: 100px">
                    Unit Price
                </th>
                <th style="width: 100px">
                     
                </th>
            </tr>
    </HeaderTemplate>
    <ItemTemplate>
        <tr>
            <td>
                <%# DataBinder.Eval(Container.DataItem, "ProductName") %>
            </td>
            <td>
                <%# DataBinder.Eval(Container.DataItem, "UnitPrice") %>
            </td>
            <td>
                <asp:LinkButton ID="lnkEdit" 
                    runat="server" 
                    CommandName="edit">
                    Edit
                </asp:LinkButton>
                 | 
                <asp:LinkButton ID="lnkDelete" 
                    runat="server" 
                    CommandName="delete">
                    Delete
                </asp:LinkButton>
            </td>
        </tr>
    </ItemTemplate>
    <EditItemTemplate>
        <tr>
            <td>
                <asp:TextBox ID="txtProductName" 
                    runat="server" 
                    Text='<%# DataBinder.Eval(Container.DataItem, "ProductName") %>'>
                </asp:TextBox>
            </td>
            <td>
                <%# DataBinder.Eval(Container.DataItem, "UnitPrice") %>
            </td>
            <td>
                <asp:LinkButton ID="lnkUpdate" 
                    runat="server" 
                    CommandName="update">
                    Update
                </asp:LinkButton>
                <asp:LinkButton ID="lnkCancel" 
                    runat="server" 
                    CommandName="cancel">
                    Cancel
                </asp:LinkButton>
            </td>
        </tr>
    </EditItemTemplate>
    <FooterTemplate>
        </table>
    </FooterTemplate>
</asp:DataList>

Above DataList control’s HTML layout will generate the following type of output after binding the data with it:

Adding Delete Command Event for DataList Control

To add Delete Command event handler for DataList control. Follow the steps given below:

1. Copy and paste the same above HTML code for DataList control in the source view of ASP.Net web page.

2. Change the web page view mode to design view and then click on DataList control to select it.

3. Press F4 to open the properties window for getting the list of DataList control properties.

4. Click the events button of properties window to change its view that will provide the list of DataList control events.

5. Then double click on DeleteCommand event to generate the OnDeleteCommand event handler in the C# code behind file to add the delete command logic there.

Above figure shows the way out for adding the Delete command event to the DataList control.

C# code for DataList Control Delete Command

protected void DataList1_DeleteCommand(object source, DataListCommandEventArgs e)
{
    // Get the DataKey value associated with current Item Index.
    int ProductID = Convert.ToInt32(DataList1.DataKeys[e.Item.ItemIndex]);

    // string variable to store the connection string
    // retrieved from the connectionStrings section of web.config
    string connectionString = ConfigurationManager.ConnectionStrings["NorthwindConnectionString"].ConnectionString;

    // sql connection object
    SqlConnection mySqlConnection = new SqlConnection(connectionString);

    // sql command object initialized with delete command text
    SqlCommand mySqlCommand = new SqlCommand("delete from products where productid=@productid", mySqlConnection);
    mySqlCommand.Parameters.Add("@productid", SqlDbType.Int).Value = ProductID;

    // check the connection state and open it accordingly.
    if (mySqlConnection.State == ConnectionState.Closed)
        mySqlConnection.Open();

    // execute sql delete query
    mySqlCommand.ExecuteNonQuery();

    // check the connection state and close it accordingly.
    if (mySqlConnection.State == ConnectionState.Open)
        mySqlConnection.Close();

    // recall the DataList databinding function
    // to refresh the DataList control data
    BindDataList();

}

When user will hit the delete link button it will execute the above C# Delete Command event code that will delete the record from SQL Database table. After executing the delete SQL command BindDataList( ) will rebind the data to DataList control to refresh DataList items.

DataList1.DataKeys[e.Item.ItemIndex] will return the value of data field added as DataKeyField of DataList control that provides the unique key or Primary key value. You can use this key value to delete the database table record associated to it.

Next we will add the ASP.Net DataList Confirm Delete Using Javascript.

Note: You can get the databinding code for DataList control from ASP.Net 2.0 DataList DataBinding using C# tutorial.

1 Responses to "ASP.Net DataList Delete Command using C#"
Thanks very good article
Leave a Comment
* required
* required
* will not be published
* optional
* hint: http://www.example.com
  • Subscribe via Email