ASP.NET

Edit a Record Using DataGrid Control in ASP.NET

Programmingempire

The following example demonstrates how to Edit a Record Using DataGrid Control in ASP.NET. Before proceeding further, you can go through these examples on DataGrid control that I have posted earlier.

Meanwhile, we use a TemplateColumn as before to display the templates. Further, each TemplateColumn contains an EditItemTemplate along with an ItemTemplate. While the ItemTemplate displays the values of the field, the EditItemTemplate shows the corresponding layout when the user clicks on the Edit button.

Further, the DataGrid contains one more type of column in its layout – EditCommandColumn. As can be seen in the following code, this particular column is included in the DataGrid as the last column. Significantly, this column displays an Edit button in front of each row. Therefore now it is possible to edit an individual record.

In order to support the Edit operation, the EditCommandColumn displays the Update and Cancel buttons when the user clicks on the Edit button. Hence, a user can update an individual record. Also, if the user clicks on the Cancel button, the Edit layout disappears and the layout generated by the ItemTemplate is shown. That is possible because we call the BindGrid() method in the CancelCommand event handler.

After creating the templates, we need to define the event handler methods for EditCommand, UpdateCommand, and CancelCommand.

Creating EditItemTemplate to Edit a Record Using DataGrid Control

<asp:DataGrid ID="DataGrid1" runat="server"
                 AutoGenerateColumns="false" DataKeyField="item_id" 
                OnCancelCommand="DataGrid1_CancelCommand" 
                OnEditCommand="DataGrid1_EditCommand" 
                OnUpdateCommand="DataGrid1_UpdateCommand"
                 BackColor="Lavender" Font-Bold="true" BorderColor="Navy"
                 BorderStyle="Outset" BorderWidth="4"
                  CellPadding="10" CellSpacing="10"
                 Font-Size="Large">
                <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>
                        <EditItemTemplate>
                            <asp:Label ID="Label5" runat="server"
                                Text='<%#DataBinder.Eval(Container,"DataItem.item_id") %>'></asp:Label>
                        </EditItemTemplate>
                    </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>
                        <EditItemTemplate>
                            <asp:TextBox ID="t1" runat="server"
                                 Text='<%#DataBinder.Eval(Container,"DataItem.item_name") %>'></asp:TextBox>
                        </EditItemTemplate>
                    </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>
                        <EditItemTemplate>
                            <asp:TextBox ID="t2" runat="server"
                                 Text='<%#DataBinder.Eval(Container,"DataItem.price") %>'></asp:TextBox>
                        </EditItemTemplate>
                    </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>
                        <EditItemTemplate>
                              <asp:TextBox ID="t3" runat="server"
                                   Text='<%#DataBinder.Eval(Container,"DataItem.quantity") %>'></asp:TextBox>
                        </EditItemTemplate>
                    </asp:TemplateColumn>
                    <asp:EditCommandColumn HeaderText="Edit" EditText="Edit"
                         CancelText="Cancel" UpdateText="Update">
                    </asp:EditCommandColumn>
                </Columns>
            </asp:DataGrid>

Events Required to Edit a Record Using DataGrid Control

The following code shows how we perform edit, update, and cancel operations with DataGrid control.

In this case, we use three event handlers. Firstly, an event handler in response to the EditCommand event. Particularly, it will set the EditItemIndex property to the index of the record for which the Edit button is clicked.

Secondly, the event handler for UpdateCommand executes the update query. At first, we retrieve the key using the DataKeys collection of the DataGrid. After that, we retrieve the values that the user has entered in the individual TextBoxes using the FindControl() method.

Now that, we have all the four parameters to formulate the update query. Basically, it is a parameterized query. Hence, the UpdateCommand event handler performs the actual update operation.

Finally, the CancelCommand event handler sets the EditItemIndex property to -1. Therefore, it cancels the Edit operation.

        protected void DataGrid1_EditCommand(object source, DataGridCommandEventArgs e)
        {
            DataGrid1.EditItemIndex = e.Item.ItemIndex;
            BindGrid();
        }

        protected void DataGrid1_UpdateCommand(object source, DataGridCommandEventArgs e)
        {
            int k = (int)DataGrid1.DataKeys[e.Item.ItemIndex];
            TextBox tx, ty, tz;
            tx = (TextBox)e.Item.FindControl("t1");
            ty = (TextBox)e.Item.FindControl("t2");
            tz = (TextBox)e.Item.FindControl("t3");

            String s1 = tx.Text.Trim();
            int a = Int32.Parse(ty.Text);
            int b = Int32.Parse(tz.Text);

            String str = "update Items set item_name=@in, price=@pr, quantity=@qu where item_id=@iid";
            Connect();
            SqlCommand cmd = new SqlCommand(str, c1);
            cmd.Parameters.AddWithValue("@iid", k);
            cmd.Parameters.AddWithValue("@in", s1);
            cmd.Parameters.AddWithValue("@pr", a);
            cmd.Parameters.AddWithValue("@qu", b);
            int n = cmd.ExecuteNonQuery();
            if (n > 0)
            {
                Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "updated", "<script>alert('Record Updated Successfully')</script>");
                DataGrid1.EditItemIndex = -1;
                c1.Close();
                BindGrid();
            }
            else
            {
                Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "updated", "<script>alert('Record Not Updated')</script>");
                DataGrid1.EditItemIndex = -1;
                c1.Close();
                BindGrid();
            }

        }
        protected void DataGrid1_CancelCommand(object source, DataGridCommandEventArgs e)
        {
            DataGrid1.EditItemIndex = -1;
            BindGrid();
        }

Output

An Example to Edit a Record Using DataGrid Control in ASP.NET
An Example to Edit a Record Using DataGrid Control in ASP.NET

In the same way, we can perform delete operation using a DataGrid. The following link provides more information on deleting a record.

Deleting a Record using DataGrid Control in ASP.NET


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...