E:\web\learnaspcom\htdocs\freebook\learn\ubtoc.xml LearnAsp.com - ASP ASP.net Free Lessons
Search Search

#1 worldwide
FREE Coding Lessons

since 1996
   THE BEST WAY to learn ASP & Asp.net!
Advertise Here!
click for details
Credits Host:
DiscountASP.net
Server Admin:
The "Team"
Contact Info.
Charles M. Carroll
<Asp.net blog>
<personal site>
xxx

XML Books
by Paul Chu

Here is codet to fully edit a XML file

   filename=/students/paulchu/xmlbookswithadd.aspx

<Test Script Below>


<%@ Import Namespace="System.IO" %>
<%@ Import Namespace="System.Data" %>

<HTML>
<%'@ Page debug=true trace=true %>
<script language="VB" runat="server"> 
'  ASP.NET concepts:
'        datagrid , datatable, datarow 
'        ReadXML, WriteXML
'        datagrid events:  edit update delete
'        system.io.File.exists Fileinfo, Streamwriter
'
' 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. Add new table to add author - add code to add a new row
' 5. Modify update and delete eventhandlers to update XML file using dataset
' 6. Hide Delete Column and Add Author panel when in edit mode
' 7. When all books have been deleted, add code to "make" a datatable
' Missing Features:
'    No Validation in add / edit 
'    
' 8. Support creating a new XML file from scratch: create a new file if it is not found
'
' Ok, before you get all excited, the job is not done
'
'   Field validation logic needs to be added
'   the Delete Book method relies on not having asp validator objects
'
'    You also need to verify that the ISBN is not already in the
'   the dataset ( or will it detect it because we have isbn defined as a key )
'
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 DataSet = new dataset()
        Dim FS As FileStream
        
  if file.exists( gXmlpath) then
        FS = New FileStream( gXmlpath , FileMode.Open) 
        ds.ReadXml(FS)
        FS.close() 
  else
        createnewfile( gxmlpath)  'create a new XML file
  end if     
                
' 02/14/02 pchu  handle an empty file ---------------------------
if  ds.tables.count = 0  then
    ds.tables.add( MakeBooksTable() ) 'create a DataTable in the dataset
end if 


' 02/14/02 pchu ---------------------------
' Add code to sort the dataview if parmsort is present
        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() 

END SUB 

' =================================

sub  createnewfile(byval filepath as string )
'-- create a new file if necessary 
    dim f as fileinfo = new fileinfo( filepath )
    dim writer as streamwriter = f.createtext()
    writer.writeline ("<books></books>") 'create a root element
    writer.close()
trace.warn ("new file created", filepath )        
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

        ' reload the XML file into a dataset
        Dim ds As New DataSet()
        ds.ReadXml( gXmlPath )

        ' 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( gXmlPath )

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

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( gXmlPath )

        ' 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

        ' save the updated data as the XML file
        ds.WriteXml( gXmlPath )

        SetEditMode( "off" )
        
        mydatagrid.EditItemIndex = -1
        dataload("")
End Sub

' =================================

sub SetEditMode ( state as string)
    select case state
        case "on"
        MyDataGrid.columns(0).visible = False    'Hide Delete Column
        panela.visible = False                    'Hide Add Author
    
        case else
        
        MyDataGrid.columns(0).visible = True    'Show Delete Column
        panela.visible = True                    'Show Add Author
        
    end select        
end sub

' =================================

public sub dg_itemcreated ( sender as object, e as datagriditemeventargs )

  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 sub

' =========================

Sub AddAuthor(ByVal sender As System.Object, ByVal e As System.EventArgs) 
trace.warn ("AddAuthor", "Beg" )

'''response.write ("<HR>Work in Progress<HR>")
'----------
        ' reload the XML file into a dataset
        Dim ds As New DataSet()
        ds.ReadXml( gXmlPath )

' 02/14/02 pchu  handle an empty file ---------------------------
if  ds.tables.count = 0  then
    ds.tables.add( MakeBooksTable() )
end if 

        ' create a new datarow object
        Dim row As DataRow =  ds.tables(0).newrow()


dim sw1 as integer = 2
select case sw1 
    case 1
Dim cols As String() = {"isbn", "author", "title", "category", "comments"}
        row( cols(0)  ) = xisbn.text
        row( cols(1)  ) = xauthor.text
        row( cols(2)  ) = xtitle.text
        row( cols(3)  ) = xcategory.text
        row( cols(4)  ) = xcomments.text
    case 2
        row( "isbn" )  = xisbn.text
        row( "author"  ) = xauthor.text
        row( "title"  ) = xtitle.text
        row( "category"  ) = xcategory.text
        row( "comments"  ) = xcomments.text
end select

        ds.tables(0).rows.add(row)  'add our datarow to the table in ds
        
        ' save the updated data as the XML file
        ds.WriteXml( gXmlPath )

'---------    
   dataload("")  ' re-display xml file
    
    ClearForm() 
    
    ' clear ADD author form 
trace.warn ("AddAuthor", "End" )    
    End Sub 

' =========================

Sub ClearForm() 
    xisbn.Text = "" 
    xauthor.Text = "" 
    xcategory.Text = "" 
    xtitle.Text = "" 
    xcomments.Text = "" 
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 by Paul Chu</font> 
<span runat="server" id="MySpan"></h3>
<h2>Updateable Datagrid and Add Form to update xml 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>
<asp:Panel ID=panela visible=True Runat=server>
<TABLE id=Table1 cellSpacing=1 cellPadding=1 width=300 border=1>
  <TR>
    <TD bgColor=lightblue colSpan=3>
      <P align=center>Add New Author</P></TD></TR>
  <TR>
    <TD>ISBN:</TD>
    <TD><asp:TextBox id=xisbn runat="server"></asp:TextBox></TD>
    <TD></TD></TR>
  <TR>
    <TD>Author:</TD>
    <TD><asp:TextBox id=xauthor runat="server"></asp:TextBox></TD>
    <TD></TD></TR>
  <TR>
    <TD>Title:</TD>
    <TD><asp:TextBox id=xtitle runat="server"></asp:TextBox></TD>
    <TD></TD></TR>
  <TR>
    <TD>Category:</TD>
    <TD><asp:TextBox id=xcategory runat="server"></asp:TextBox></TD>
    <TD></TD></TR>
  <TR>
    <TD>Comments:</TD>
    <TD><asp:TextBox id=xcomments runat="server" TextMode="MultiLine"></asp:TextBox></TD>
    <TD></TD></TR>
  <TR>
    <TD colSpan=3>
      <P align=center><asp:Button id=btnSubmit onclick=AddAuthor runat="server" Text="Add Author"></asp:Button></P></TD></TR></TABLE>
<P>&nbsp;</P> 
</asp:Panel>

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