Article Options
Premium Sponsor
Premium Sponsor

 »  Home  »  Web Development  »  Using ASP.NET DataGrid Web Server Control  »  DataGrid editing
 »  Home  »  Web Development  »  ASP.NET  »  Using ASP.NET DataGrid Web Server Control  »  DataGrid editing
Using ASP.NET DataGrid Web Server Control
by Misha Zhutov | Published  11/03/2005 | Web Development ASP.NET | Rating:
DataGrid editing

As we already know, a TemplateColumn has two control sets for viewing and editing mode. First of all, we need to add an Edit button to DataGrid.
A column with Edit link can be added either as the first column or as last column in the DataGrid.
I prefer to add Edit link as the  DataGrid’s first column. This is because, sometimes, DataTable can have many columns and a user needs to scroll horizontally.
Let’s take a look at the HTML code in the ASPX page that creates the DataGrid column with links:

<asp:TemplateColumn>
  <ItemStyle HorizontalAlign="Center" VerticalAlign="Middle"></ItemStyle>
  <ItemTemplate>
    <asp:LinkButton id="LinkEdit" runat="server" CommandName="Edit" Text="Edit"></asp:LinkButton>
  </ItemTemplate>
  <EditItemTemplate>
    <asp:LinkButton id="LinkUpdate" runat="server"
CommandName="Update" Text="Update"></asp:LinkButton>
    <asp:LinkButton id="LinkCancel" runat="server"
CausesValidation=False CommandName="Cancel" Text="Cancel"></asp:LinkButton>
  </EditItemTemplate>
</asp:TemplateColumn>

So, we have Edit link visible in view mode and Update, Cancel links visible in edit mode. User can edit any fields by typing in TextBoxes, changing selected value in DropDownLists or changing value in CheckBoxes.
After that, user can hit Update link to accept changes to database or Cancel link to return to view mode without changing anything.
Developer must also add code to DataGrid.EditCommand Event handler such way:

Private Sub ProductsDataGrid_EditCommand(ByVal source As Object_
ByVal e As System.Web.UI.WebControls.DataGridCommandEventArgs) _
Handles ProductsDataGrid.EditCommand
  ProductsDataGrid.EditItemIndex = e.Item.ItemIndex
  BindDataGrid()
End Sub
Generated using PrettyCode.Encoder

Validating user inputs

In some cases the user can enter incorrect values during editing. Validators prevent the user from doing that.
You can use as many validators as you want in different columns. But how to output errors in one single place? The answer is a ValidationSummary contol which displays messages from all validators in a single place. I used RequiredFieldValidator for ProductName and QuantityPerUnit fields and CompareValidator for UnitPrice, UnitsInStock, ReorderLevel field which checked that user input a correct type of a value.
Here is a screenshot of the “validation” on web form:

Sponsored Links