Walkthrough: Using a DataGrid Web Control to Read and Write Data

J

Joe Au

I follow the Walkthrough documented on Visual Studio to create an editable
data grid but it does not work on getting the value of the textbox in the
data grid. The code is copied here. I mark "*****" at which the categoryName
always get the past value no matter what it has been changed. How do I fix
it? Thanks.
Joe.


Private Sub DataGrid1_UpdateCommand(ByVal source As Object, ByVal e As
System.Web.UI.WebControls.DataGridCommandEventArgs) Handles
DataGrid1.UpdateCommand
Dim categoryName, categoryDescription As String

' Gets the value of the key field of the row being updated
Dim key As String = DataGrid1.DataKeys(e.Item.ItemIndex).ToString()

' Gets get the value of the controls (textboxes) that the user
' updated. The DataGrid columns are exposed as the Cells collection.
' Each cell has a collection of controls. In this case, there is only
one
' control in each cell -- a TextBox control. To get its value,
' you copy the TextBox to a local instance (which requires casting)
' and extract its Text property.
'
' The first column -- Cells(0) -- contains the Update and Cancel
buttons.
Dim tb As TextBox

' Gets the value the TextBox control in the third column
******
tb = CType(e.Item.Cells(2).Controls(0), TextBox)
categoryName = tb.Text

' Gets the value the TextBox control in the fourth column
tb = CType(e.Item.Cells(3).Controls(0), TextBox)
categoryDescription = tb.Text

' Finds the row in the dataset table that matches the
' one the user updated in the grid. This example uses a
' special Find method defined for the typed dataset, which
' returns a reference to the row.
Dim r As dsCategories.CategoriesRow
r = DsCategories1.Categories.FindByCategoryID(key)

' Updates the dataset table.
r.CategoryName = categoryName
r.Description = categoryDescription

' Calls a SQL statement to update the database from the dataset
SqlDataAdapter1.Update(DsCategories1)

' Takes the DataGrid row out of editing mode
DataGrid1.EditItemIndex = -1

' Refreshes the grid
DataGrid1.DataBind()
End Sub
 
S

S. Justin Gengo

Joe,

You are probably re-populating your datagrid on each page load and thus
resetting all the data before you are reading it.

Wherever you are populating the datagrid wrap that code in an if then so it
only gets populated on the intial page load like this:

If Not Page.IsPostBack Then
'---Populate your datagrid here
End If

--
Sincerely,

S. Justin Gengo, MCP
Web Developer / Programmer

www.aboutfortunate.com

"Out of chaos comes order."
Nietzsche
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,057
Latest member
KetoBeezACVGummies

Latest Threads

Top