ASP.NET

Deleting a Record using DataGrid Control in ASP.NET

Programmingempire

The following example shows Deleting a Record using DataGrid Control in ASP.NET. To begin with, first, understand what is a DataGrid control and how to use it in a Web Form. For this purpose, you can go through following articles to get an understanding of the DataGrid control.

Example Demonstrating Deleting a Record using DataGrid Control

As I have shown earlier, the DataGrid comprises various types of columns. Therefore, in this example, a ButtonColumn is also included along with TemplateColumns. Further, the DataGrid also handles the DeleteCommand event to perform the delete operation.

            <asp:DataGrid ID="DataGrid1" runat="server"
                 AutoGenerateColumns="false" DataKeyField="item_id" 
                 BackColor="Lavender" Font-Bold="true" BorderColor="Navy"
                 BorderStyle="Outset" BorderWidth="4"
                  CellPadding="10" CellSpacing="10"
                 Font-Size="Large" OnDeleteCommand="DataGrid1_DeleteCommand">
                <Columns>
                    <asp:TemplateColumn>
                        <HeaderStyle BackColor="LightBlue" ForeColor="Navy"/>
                        <HeaderTemplate>
                            Item ID
                        </HeaderTemplate>
                        <ItemTemplate>
                            <asp:Label ID="Label1" runat="server"
                                Text='<%#DataBinder.Eval(Container,"DataItem.item_id") %>'></asp:Label>
                        </ItemTemplate>
                    </asp:TemplateColumn>
                    <asp:TemplateColumn>
                        <HeaderStyle BackColor="LightBlue" ForeColor="Navy"/>
                        <HeaderTemplate>
                            Item Name
                        </HeaderTemplate>
                        <ItemTemplate>
                           <asp:Label ID="Label2" runat="server" 
                               Text='<%#DataBinder.Eval(Container,"DataItem.item_name") %>'></asp:Label>
                        </ItemTemplate>
                    </asp:TemplateColumn>
                    <asp:TemplateColumn>
                        <HeaderStyle BackColor="LightBlue" ForeColor="Navy"/>
                        <HeaderTemplate>
                            Price
                        </HeaderTemplate>
                        <ItemTemplate>
                            <asp:Label ID="Label3" runat="server" 
                                Text='<%#DataBinder.Eval(Container,"DataItem.price") %>'></asp:Label>
                        </ItemTemplate>
                    </asp:TemplateColumn>
                    <asp:TemplateColumn>
                        <HeaderStyle BackColor="LightBlue" ForeColor="Navy"/>
                        <HeaderTemplate>
                            Quantity
                        </HeaderTemplate>
                        <ItemTemplate>
                            <asp:Label ID="Label4" runat="server" 
                                Text='<%#DataBinder.Eval(Container,"DataItem.quantity") %>'></asp:Label>
                        </ItemTemplate>
                    </asp:TemplateColumn>
                    <asp:ButtonColumn HeaderText="Delete" CommandName="Delete" Text="[Remove]">

                    </asp:ButtonColumn>
                </Columns>
            </asp:DataGrid>

The following DataGrid layout is generated by the above code.

A ButtonColumn in a DataGrid
A ButtonColumn in a DataGrid

Since, DeleteCommand event handler executes when the user clicks on the [Remove] button, the delete query is executed in the corresponding event handler.

In order to perform the delete operation, first, we retrieve the value of the corresponding key using the DataKeys collection of the DataGrid. After that, we formulate the parameterized query with the specific value of the key as a parameter. The following code shows the delete operation.

       protected void DataGrid1_DeleteCommand(object source, DataGridCommandEventArgs e)
        {
            int k = (int)DataGrid1.DataKeys[e.Item.ItemIndex];

            String str = "delete Items where item_id=@iid";
            Connect();
            SqlCommand cmd = new SqlCommand(str, c1);


            cmd.Parameters.AddWithValue("@iid", k);

            int n = cmd.ExecuteNonQuery();
            if (n > 0)
            {
                Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "deleted", "<script>alert('Record Deleted Successfully')</script>");
                DataGrid1.EditItemIndex = -1;
                c1.Close();
                BindGrid();
            }
            else
            {
                Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "deleted", "<script>alert('Record Not Deleted')</script>");
                DataGrid1.EditItemIndex = -1;
                c1.Close();
                BindGrid();
            }
        }

As can be seen, when a user clicks on the [Remove] button, the corresponding record is deleted.

Output

Example of Deleting a Record using DataGrid Control in ASP.NET
Example of Deleting a Record using DataGrid Control in ASP.NET

In order to find the complete code of insert, delete, update, and select operations using DataGrid, click on the following link.

Further Reading

Parameter and ParameterCollection in ADO.NET

Database Manipulation Using DataGrid

Example of Button and Link Button Control in ASP.NET

Example of Chart Control in ASP.NET

Creating a DataTable from a DataReader in ASP.NET

Deleting a Record using DataGrid Control in ASP.NET

Edit a Record Using DataGrid Control in ASP.NET

Insert a Record Using ItemCommand Event in DataGrid

CRUD Operations with DataGrid in ASP.NET

Creating Columns in a DataGrid Control

XML Documents and DataSet in ASP.NET

Code Render Block in ASP.NET

ASP.NET Core Features and Advantages

Display Images Using DataList Control

Adding Images Using Image Control

Creating a Group of Radio Buttons Using RadioButtonList Control

Example of Button Control in ASP.NET

Using MD5 Hash Algorithm

ItemDataBound Event in DataList

More Features of DataList in ASP.NET

A Simple Example of Using a DataList Control in ASP.NET

Properties and Methods of DataList Control in ASP.NET

ASP.NET Practice Exercise

Exploring DataList Control in ASP.NET

Custom Validator Control in ASP.NET

Validation Summary Control in ASP.NET

Validation Controls Examples – RequiredFieldValidator, CompareValidator, and RangeValidator

An Example of Data Binding with RadioButtonList Control

Binding Data to Web Control in ADO.NET

Examples of AdRotator Control in ASP.NET

Examples of Validation Controls in ASP.NET

Overview of MVC architecture in ASP.NET

programmingempire

You may also like...