The datagrid has a predefined editColumn for handling the editing of a
datagrid. Adding this simple column definition to a datagrid adds a powerful
feature. When a row is not in edit mode the column item shows the word (or
button dependant upon link type) Edit. Clicking on this link will change
the row into edit mode. Convertng items into text boxes and changing the
link edit to the two links update and delete.
To add an edit Button to a datagrid we need to add a few blocks of code.
-
In the datagrid header
-
In the column definitions of the datagrid add another column
-
In the code behind add an event handler for the edit button
-
In the code behind add an event handler for the update button
-
In the code behind add an event handler for the cancel button
-
Ensure that the postback is handled correctly
Datagrid header
OnEditCommand="doPurchasingEdit"
OnUpdateCommand="doPurchasingUpdate"
OnDeleteCommand="doPurchasingDelete"
Column definitions of the datagrid
<asp:editcommandcolumn buttontype="LinkButton"
UpdateText="Update" cancelText=Cancel"
EditText="Edit"></ASP:EditCommandColumn>
Code behind edit button event handler
Sub myDataGridEdit(ByVal
sender As Object,
ByVal e As
DataGridCommandEventArgs)
myDataGrid.EditItemIndex
= e.Item.ItemIndex
BindDataGrid()
End Sub
'myDataGridEdit
Code behind update button event handler
Sub myDataGridCancel(ByVal
sender As Object,
ByVal e As
DataGridCommandEventArgs)
myDataGrid.EditItemIndex = -1
BindPataGrid()
End Sub
'dmyDataGridCancel
Code behind cancel button event handler
Sub myDataGridUpdate(ByVal
sender As Object,
ByVal e As
DataGridCommandEventArgs)
If e.CommandName =
"Update" Then
Dim
id As Integer
= e.Item.Cells(0).Text
Dim
name As String
= CType(e.Item.FindControl("Name"),
TextBox).Text
Dim
description As
String = CType(e.Item.FindControl("Description"),
TextBox).Text
Dim
price As String
= CType(e.Item.FindControl("price"),
TextBox).Text
'Create the appropriate SQL statement
Dim
myConnection As
SqlConnection
Dim
myCommand As
SqlCommand
Dim
myDataReader As
SqlDataReader
Dim
strSQL As
String
strSQL = "UPDATE table SET name = '" & name & "', description = '"
& description & "', price = " & price &
" WHERE id = " & id
myConnection =
New SqlConnection(ConfigurationSettings.AppSettings("MyDSN"))
myCommand = New
SqlCommand(strSQL, myConnection)
Dim
myDataSet As
DataSet
myConnection.Open()
myDataReader =
myCommand.ExecuteReader()
myConnection.Close()
'Rebind the DataGrid
myDataGrid.EditItemIndex = -1
BindmyDataGrid()
myDataGrid.Visible =
True
End
If
End
Sub
Postback
If IsPostBack =
True Then
Else
BindDataGrid()
End if