|
xxx
XML Books
by Paul Chu
Here is codet to fully edit a XML file
filename=/students/paulchu/xmlbooks.aspx
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.IO" %>
<%@ Page debug="true" trace="true" %>
<HTML>
<script language="VB" runat="server">
' 02/14/02 -Enhancements to original version by Paul Chu
' 1. add code to support sorting
' 2. add code to support actual Updating and Deleting of XML data
' 3. add code to use javascript to confirm delete
' 4. insert a blank top at the top of datagrid - add code to add a new row
' 5. Modify update and delete eventhandlers to update XML file using dataset
' Blank Row in Datagrid Concept
' A datagrid is bound to a datasource e.g.datatables which
' has rows of data to disply.
' If we add a new row of data to the datatable then it will
' also show in the datagrid.
' This basic concept enables us to use the datagrid to update a new row
' and the current eventhandler code will handle the "insert"
' just like an update of an existing datarow in the dataset.
' The trick is that the new row in the dataset is all we need
' to update to fool the datagrid.
' ========================================
dim gXmlfile as string = "/experiments/data/paulchubooks.xml" ' <============ your file
dim gXmlPath as string
' =================================
Sub Page_Load(Src As Object, E As EventArgs)
gxmlpath = server.mappath( gXmlfile ) 'file is in same folder as page
If Not (IsPostBack)
DataLoad("isbn") '-- sort by ISBN
End If
End Sub
' ========================================
Sub DataLoad(parmsort as string)
Dim ds As New DataSet
Dim FS As New FileStream(Server.MapPath(gXmlFile), FileMode.Open)
ds.ReadXml(FS)
' 02/14/02 pchu handle an empty file ---------------------------
if ds.tables.count = 0 then
ds.tables.add( MakeBooksTable() )
end if
trace.warn ( "rowcount1 = " , cstr(ds.Tables(0).rows.count ))
' 02/14/02 pchu ---------------------------
' Add code to sort the dataview if parmsort is present
'ok let's get fancy and insert a blank row at the top
dim sw1 as integer = 1
select case sw1
case 1
dim dr as datarow = ds.Tables(0).newrow()
'put something in the first column ISBN
dr("ISBN") = " Add ISBN"
ds.Tables(0).rows.insertat(dr, 0)
trace.warn ( "rowcount2 = " , cstr(ds.Tables(0).rows.count ))
end select
'create dv and bind it to datagrid
dim dv as dataview
dv = new DataView(ds.Tables(0))
if parmsort.length > 0 then
dv.sort = parmsort
end if
MyDataGrid.DataSource = dv
'old MyDataGrid.DataSource = new DataView(ds.Tables(0))
' 02/14/02 pchu ---------------------------
MyDataGrid.DataBind()
FS.close()
END SUB
' ========================================
Sub DataSort(Src As Object, E As DataGridSortCommandEventArgs)
' Bug if we sort, then Edit Item Becomes Wrong
IF MyDataGrid.EditItemIndex=-1 THEN
DataLoad(e.sortexpression)
ELSE
response.write ("Can't sort until editing is done!")
END IF
End Sub
' ========================================
Sub DataDelete(Sender As Object, E As DataGridCommandEventArgs)
DIM deletekey as string
IF MyDataGrid.EditItemIndex=-1 THEN
deletekey=MyDataGrid.DataKeys(CInt(E.Item.ItemIndex))
response.write ("Delete completed for key = " & deletekey)
ELSE
response.write ("Can't delete until editing is done!")
END IF
'' Dim currentRow As Integer = e.Item.DataSetIndex
'ok too!
Dim currentRow As Integer = e.Item.itemindex
'02/16/02 BugFix: because the datagrid has an insert row which is NOT in the
' in the dataset table, we have to subtract one to compensate for the that fact
currentrow = currentrow - 1 'bug fix: subtract 1 because the grid has a insert row
trace.warn (" current row to delete ", cstr(currentrow) )
' reload the XML file into a dataset
Dim ds As New DataSet()
ds.ReadXml(Server.MapPath(gXmlFile))
' get a reference to this row of data
Dim row As DataRow = ds.Tables(0).Rows( currentrow )
row.delete() '-- kill this row in the dataset
' save the updated dataset to the XML file
ds.WriteXml(Server.MapPath(gXmlFile))
mydatagrid.EditItemIndex = -1 'exit delete mode
dataload("") ' redisplay and rebind datagrid
END SUB
' ========================================
Sub DataEdit(Sender As Object, E As DataGridCommandEventArgs)
DIM editkey as string
trace.warn ("e.item.itemindex = ", cstr(e.item.itemindex) )
MyDataGrid.EditItemIndex = Cint(E.Item.ItemIndex )
editkey=MyDataGrid.DataKeys(CInt(E.Item.ItemIndex))
trace.warn ("page.aspx", "To Be Edited" & editkey)
SetEditMode( "on" )
DataLoad("")
End Sub
' ========================================
Sub DataCancel(Sender As Object, E As DataGridCommandEventArgs)
MyDataGrid.EditItemIndex = -1
trace.warn ("page.aspx", "edit was cancelled")
SetEditMode( "off" )
DataLoad("")
End Sub
'====================================================
Public Sub DataUpdate(ByVal source As Object, ByVal e _
As System.Web.UI.WebControls.DataGridCommandEventArgs)
'This eventhandler will process both an Update and a Add because in both
' cases the dataset has an existing row to "update", because we added a
' dummy row to the dataset table for the add
Dim cols As String() = {"isbn", "author", "title", "category", "comments"}
Dim numCols As Integer = e.Item.Cells.Count
Dim currentRow As Integer = e.Item.DataSetIndex
' reload the XML file into a dataset
Dim ds As New DataSet()
ds.ReadXml(Server.MapPath(gXmlFile))
dim row as datarow
trace.warn("update row = ", currentrow.tostring() )
trace.warn("datasetindex row = ", e.Item.DataSetIndex.tostring() )
' 02/14/02 pchu handle an empty file ---------------------------
if ds.tables.count = 0 then
ds.tables.add( MakeBooksTable() )
end if
if currentrow = 0 then
row = ds.tables(0).newrow()
else
Row = ds.Tables(0).Rows(e.Item.DataSetIndex - 1) 'need to sub 1 because we have an inserted row
end if
' get a reference to this row of data
'' Dim row As DataRow = ds.Tables(0).Rows(e.Item.DataSetIndex)
' get the values and update the datarow
Dim I, J As Integer
j = -1
Trace.Warn("aspx.page", "numcols = " & CStr(numCols))
For I = 2 To numCols - 1 'skip first and 2nd columns (Edit/Delete command column)
j += 1
Dim currentTextBox As TextBox
currentTextBox = CType(e.Item.Cells(I).Controls(0), TextBox )
row(cols(j)) = currentTextBox.Text
Trace.Warn(I.ToString(), CStr(cols(j)) & " = " & currentTextBox.Text)
Next
if currentrow = 0 then
ds.tables(0).rows.insertat(row, 0 )
end if
' save the updated data as the XML file
ds.WriteXml(Server.MapPath(gXmlFile))
mydatagrid.EditItemIndex = -1
SetEditMode( "off" )
dataload("")
End Sub
' ===================================
public sub dg_itemcreated ( sender as object, e as datagriditemeventargs )
'-- add logic to modify EDIT and Suppress the Delete
if e.item.itemindex = 0 then 'first row
'reference the delete button
'???????????????????? can we use FindControl here to locate controls
dim lbDelete as linkbutton = e.item.cells(0).controls(0)
dim lbEdit as linkbutton = e.item.cells(1).controls(0)
trace.warn ("page.aspx", "lbDelete = " & lbDelete.text )
trace.warn ("page.aspx", "lbEdit = " & lbEdit.text )
if lbDelete.text = "Delete Book" then
lbDelete.text = ""
end if
if lbEdit.text = "Edit" then
lbEdit.text = "AddNew"
end if
if lbEdit.text = "Update" then
lbEdit.text = "Insert"
end if
end if
if e.item.itemindex > 0 then 'first row
select case e.item.itemtype
case listitemtype.item
dim mydeletebutton as tablecell
mydeletebutton = e.item.cells(0)
mydeletebutton.attributes.add("onclick", _
"return confirm('Are you sure you want to Delete ?');" )
case listitemtype.alternatingitem
dim mydeletebutton as tablecell
mydeletebutton = e.item.cells(0)
mydeletebutton.attributes.add("onclick", _
"return confirm('Are you sure you want to Delete ?');" )
end select
end if
end sub
' =========================
sub SetEditMode ( state as string)
select case state
case "on"
MyDataGrid.columns(0).visible = False 'Hide Delete Column
case else
MyDataGrid.columns(0).visible = True 'Show Delete Column
end select
end sub
' ========================================
Private Function MakeBooksTable() As DataTable
'' theColumn.DefaultValue = "Fname"
' Dim fNameColumn As DataColumn = New DataColumn()
'' idColumn.AutoIncrement = True
' Create a new DataTable titled 'Books.'
Dim theTable As DataTable = new DataTable("Books")
' Add three column objects to the table.
Dim theColumn1 As DataColumn = new DataColumn()
theColumn1.DataType = System.Type.GetType("System.String")
theColumn1.ColumnName = "isbn"
theTable.Columns.Add(theColumn1)
Dim theColumn2 As DataColumn = new DataColumn()
theColumn2.DataType = System.Type.GetType("System.String")
theColumn2.ColumnName = "author"
theTable.Columns.Add(theColumn2)
Dim theColumn3 As DataColumn = new DataColumn()
theColumn3.DataType = System.Type.GetType("System.String")
theColumn3.ColumnName = "title"
theTable.Columns.Add(theColumn3)
Dim theColumn4 As DataColumn = new DataColumn()
theColumn4.DataType = System.Type.GetType("System.String")
theColumn4.ColumnName = "category"
theTable.Columns.Add(theColumn4)
Dim theColumn5 As DataColumn = new DataColumn()
theColumn5.DataType = System.Type.GetType("System.String")
theColumn5.ColumnName = "comments"
theTable.Columns.Add(theColumn5)
' Create an array for DataColumn objects.
Dim keys(0) As DataColumn
keys(0) = theColumn1
theTable.PrimaryKey = keys
' Return the new DataTable.
MakeBooksTable = theTable
End Function
' ========================================
</script>
<!-- =================================================== -->
<body>
<h3><font face="Verdana">The Best Books Ever: Enhanced Version 2 by Paul Chu</font>
<span runat="server" id="MySpan"></h3>
<h2>Updateable Datagrid with Blank Row update file: <% = gxmlfile %></h2>
<form runat="server">
<P>
<ASP:DataGrid id="MyDataGrid" runat="server"
AllowSorting="True"
OnSortCommand="DataSort"
OnDeleteCommand="DataDelete"
OnEditCommand="DataEdit"
OnCancelCommand="DataCancel"
OnUpdateCommand="DataUpdate"
DataKeyField="isbn"
Width="100%"
BackColor="White"
BorderColor="Black"
CellPadding=3
Font-Name="Verdana"
Font-Size="8pt"
Headerstyle-BackColor="lightblue"
Headerstyle-Font-Size="10pt"
Headerstyle-Font-Style="bold"
MaintainState="true"
Font-Names="Verdana"
onitemcreated="dg_itemcreated"
>
<HeaderStyle Font-Size="10pt" BackColor="LightBlue">
</HeaderStyle>
<Columns>
<asp:ButtonColumn Text="Delete Book" CommandName="Delete"></asp:ButtonColumn>
<asp:EditCommandColumn ButtonType="LinkButton" UpdateText="Update" CancelText="Cancel" EditText="Edit">
<ItemStyle Wrap="False">
</ItemStyle>
</asp:EditCommandColumn>
</Columns>
</ASP:DataGrid></P>
</form></SPAN>
</body>
</HTML>
 |  |  |
 |
There are many worthy charities!!. But perhaps help starving children in Africa or South America AND help Charles too.
a $5 tip buys him lunch at McDonalds,
a $20 tip buys his kid Hitoshi a new computer game,
a $39 tip buys his daughter Michiko a few nice outfits.
See our donor list.
|  |
 |  |  |
|
|
|
|