ASP.Net/XML/XML Edit

Материал из .Net Framework эксперт
Перейти к: навигация, поиск

Edit XML data through DataSet in C#

<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.OleDb" %>
<script Language="c#" runat="server">
  void Page_Load(object sender, EventArgs e)
  {
    DataSet objDataSet = new DataSet();
    // Read in the XML file
    objDataSet.ReadXml(Server.MapPath("NewEmployees.xml"));
    // Show it in a grid
    dgEmployees1.DataSource = objDataSet.Tables[0].DefaultView;
    dgEmployees1.DataBind();
    // Modify a row
    objDataSet.Tables["employee"].Rows[0]["firstName"] = "A";
    objDataSet.Tables["employee"].Rows[0]["lastName"] = "B";
    // Add a new row to the table
    DataTable objTable = null;
    DataRow objNewRow = null;
    objTable = objDataSet.Tables["employee"];
    objNewRow = objTable.NewRow();
    objNewRow["firstName"] = "C";
    objNewRow["lastName"] = "D";
    objTable.Rows.Add(objNewRow);
    // Save it to a new file
    objDataSet.WriteXml(Server.MapPath("Employees2.xml"));
    // Read in the new file
    DataSet objDataSet2 = new DataSet();
    objDataSet2.ReadXml(Server.MapPath("Employees2.xml"));
    // Show it in another grid
    dgEmployees2.DataSource = objDataSet2.Tables[0].DefaultView;
    dgEmployees2.DataBind();
  }
</script>
<html>
 <body>
  <table>
   <tr>
    <td valign="top"><asp:DataGrid id="dgEmployees1" runat="server" /></td>
    <td valign="top"><asp:DataGrid id="dgEmployees2" runat="server" /></td>
   </tr>
  </table>
 </body>
</html>

<%--NewEmployees.xml
<?xml version="1.0"?>
<employees>
  <employee id="1">    
      <firstName>Nancy</firstName>
      <lastName>Lee</lastName> 
    <city>Seattle</city>
    <state>WA</state>
    <zipCode>98122</zipCode>   
  </employee>
  <employee id="2">    
      <firstName>Jason</firstName>
      <lastName>Wang</lastName>
    <city>Vancouver</city>
    <state>WA</state>
    <zipCode>98123</zipCode>   
  </employee> 
</employees>
--%>



Use asp datagrid to edit data in XML

<%--
Beginning ASP.NET 1.0 with C# (Paperback)
by David Sussman, Chris Ullman, 
   Juan T. Llibre, John Kauffman, 
   Ollie Cornes, Ajoy Krishnamoorthy, 
   Srinivasa Sivakumar, Chris Goode, 
   Neil Raybould, Christopher Miller, 
   Rob Birdwell, Matt Butler, Gary Johnson 
   
# Publisher: Wrox Press; 1st edition (June 2002)
# Language: English
# ISBN: 1861007345
--%>

<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.IO" %>
<%@ Import Namespace="System.Globalization" %>
<script Language="c#" runat="server">
  void Page_Load(object sender, EventArgs e)
  {
    if (!(Page.IsPostBack))
    {
      EventData.DataSource = LoadMyCalendarData();
      EventData.DataBind();
    }
  }
  protected DataSet LoadMyCalendarData()
  {
     string sourceXml = Server.MapPath("MyCalendar.xml");
      if (!(File.Exists(sourceXml)))
      {
         return null;
      }
     DataSet cachedDataSet = (DataSet)Session["MyCalendarData"];
     if (!(cachedDataSet == null))
     {
        return cachedDataSet;
     }
    DataSet dataSet = new DataSet();
    try
    { 
       dataSet.ReadXml(sourceXml);
       Session["MyCalendarData"] = dataSet;
    }
    catch (Exception e)
    {
       ErrorMessage.Text = e.Message;
       dataSet = null;
    }
    return dataSet;
  }
  void DEDR_Edit(object sender, DataGridCommandEventArgs e)
  {
     EventData.EditItemIndex = Convert.ToInt32(e.Item.ItemIndex);
     EventData.DataSource = LoadMyCalendarData();
     EventData.DataBind();
  }
  void DEDR_Update(object sender, DataGridCommandEventArgs e)
  {
     DataSet dataSet  = LoadMyCalendarData();
     int row = Convert.ToInt32(e.Item.ItemIndex);
     TextBox EditText = null;
     EditText = (TextBox)e.Item.FindControl("txtShortDesc");
     dataSet.Tables[0].Rows[row]["ShortDesc"] = EditText.Text;
     EditText = (TextBox)e.Item.FindControl("txtDetailDesc");
     dataSet.Tables[0].Rows[row]["DetaiLDesc"] = EditText.Text;
     EditText = (TextBox)e.Item.FindControl("txtEventDate");
     dataSet.Tables[0].Rows[row]["EventDate"]= EditText.Text;
     EditText = (TextBox)e.Item.FindControl("txtStartTime");
     dataSet.Tables[0].Rows[row]["StartTime"] = EditText.Text;
     EditText = (TextBox)e.Item.FindControl("txtEndTime");
     dataSet.Tables[0].Rows[row]["EndTime"] = EditText.Text;
     dataSet.WriteXml(Server.MapPath("MyCalendar.xml"));
     Session["MyCalendarData"] = null;
     EventData.EditItemIndex = -1;
     EventData.DataSource = LoadMyCalendarData();
     EventData.DataBind();
  }
  void DEDR_Cancel(object sender, DataGridCommandEventArgs e)
  {
    EventData.EditItemIndex = -1;
    Session["MyCalendarData"] = null;
    EventData.DataSource = LoadMyCalendarData();
    EventData.DataBind();
  }
  void DEDR_Delete(object sender, DataGridCommandEventArgs e)
  {
    DataSet dataSet = LoadMyCalendarData();
    int row = Convert.ToInt32(e.Item.ItemIndex);
    dataSet.Tables[0].Rows[row].Delete();
    dataSet.WriteXml(Server.MapPath("MyCalendar.xml"));
    Session["MyCalendarData"] = null;
    EventData.EditItemIndex = -1;
    EventData.DataSource = LoadMyCalendarData();
    EventData.DataBind();
  }
  void DEDR_Add(object sender, EventArgs e)
  {
    DataSet dataSet = LoadMyCalendarData();
    DataRow newRow;
    newRow = dataSet.Tables[0].NewRow();
    newRow["ShortDesc"] = "";
    newRow["DetailDesc"] = "";
    newRow["EventDate"] = "";
    newRow["StartTime"] = "";
    newRow["EndTime"] = "";
    dataSet.Tables[0].Rows.Add(newRow);
    dataSet.WriteXml(Server.MapPath("MyCalendar.xml"));
    Session["MyCalendarData"] = null;
    EventData.DataSource = LoadMyCalendarData();
    EventData.DataBind();
    EventData.EditItemIndex = EventData.Items.Count - 1;
    EventData.DataSource = LoadMyCalendarData();
    EventData.DataBind();
  }
</script>

<html>
  <body>
    <form runat="server">
      <asp:Label id="ErrorMessage" runat="server" /><br/>
      <asp:LinkButton OnClick="DEDR_Add" Text="Add new event"
           runat="server"/><br/>
      <asp:DataGrid id="EventData"
           AutoGenerateColumns="false" width="100%" runat="server"
           OnEditCommand="DEDR_Edit"
           OnUpdateCommand="DEDR_Update"
           OnCancelCommand="DEDR_Cancel"
           OnDeleteCommand="DEDR_Delete">
        <HeaderStyle ForeColor="White" BackColor="DodgerBlue"
                     Font-Bold="true"/>
        <ItemStyle BackColor="White"/>
        <AlternatingItemStyle BackColor="Gainsboro"/>
        <Columns>
          <asp:TemplateColumn HeaderText="Date">
            <ItemTemplate>
              <%# DataBinder.Eval(Container.DataItem, "EventDate") %>
            </ItemTemplate>
            <EditItemTemplate>
              <asp:TextBox id="txtEventDate" Size="25";
                   Text="<%# DataBinder.Eval(Container.DataItem,"EventDate") %>"
                   runat="server"/>
            </EditItemTemplate>
          </asp:TemplateColumn>
          <asp:TemplateColumn HeaderText="Event">
            <ItemTemplate>
              <%# DataBinder.Eval(Container.DataItem, "ShortDesc") %>
            </ItemTemplate>
            <EditItemTemplate>
              <asp:TextBox id="txtShortDesc" Size="25";
                   Text="<%# DataBinder.Eval(Container.DataItem,"ShortDesc") %>"
                   runat="server"/>
            </EditItemTemplate>
          </asp:TemplateColumn>
          <asp:TemplateColumn HeaderText="Description">
            <ItemTemplate>
              <%# DataBinder.Eval(Container.DataItem, "DetailDesc") %>
            </ItemTemplate>
            <EditItemTemplate>
              <asp:TextBox id="txtDetailDesc" Size="50"
                 Text="<%# DataBinder.Eval(Container.DataItem, "DetailDesc") %>"
                   runat="server"/>
            </EditItemTemplate>
          </asp:TemplateColumn>
          <asp:TemplateColumn HeaderText="Start Time">
            <ItemTemplate>
              <%# DataBinder.Eval(Container.DataItem, "StartTime") %>
            </ItemTemplate>
            <EditItemTemplate>
              <asp:TextBox id="txtStartTime" Size="7"
                   Text="<%# DataBinder.Eval(Container.DataItem, "StartTime") %>"
                   runat="server"/>
            </EditItemTemplate>
          </asp:TemplateColumn>
          <asp:TemplateColumn HeaderText="EndTime">
            <ItemTemplate>
              <%# DataBinder.Eval(Container.DataItem, "EndTime") %>
            </ItemTemplate>
            <EditItemTemplate>
              <asp:TextBox id="txtEndTime" Size="7"
                   Text="<%# DataBinder.Eval(Container.DataItem, "EndTime") %>"
                   runat="server"/>
            </EditItemTemplate>
          </asp:TemplateColumn>
          <asp:TemplateColumn>
            <ItemTemplate>
              <asp:LinkButton CommandName="Edit"   Text="Edit"
                   runat="server"/>
              <asp:LinkButton CommandName="Delete" Text="Delete"
                   runat="server"/>
            </ItemTemplate>
            <EditItemTemplate>
              <asp:LinkButton CommandName="Cancel" Text="Cancel"
                   runat="server"/>
              <asp:LinkButton CommandName="Update" Text="Update"
                   runat="server"/>
            </EditItemTemplate>
          </asp:TemplateColumn>
        </Columns>
    </asp:DataGrid>
    </form>
  </body>
</html>

<%--
<?xml version="1.0" standalone="yes"?>
<MyCalendar>
  <Event>
    <ShortDesc>Gig in Portland - Jazz Club</ShortDesc>
    <DetailDesc>This should be fun - playing J &amp; T again - be sure to bring the charts.</DetailDesc>
    <EventDate>2002/07/02</EventDate>
    <StartTime>6:00PM</StartTime>
    <EndTime>11:30PM</EndTime>
  </Event>
  <Event>
    <ShortDesc> Rehearsal - Brigadoon</ShortDesc>
    <DetailDesc>Community Theatre orchestra rehearsal - bring mutes.</DetailDesc>
    <EventDate>2002/07/14</EventDate>
    <StartTime>3:30PM</StartTime>
    <EndTime>6:30PM</EndTime>
  </Event>
  <Event>
    <ShortDesc>.NET Training Class</ShortDesc>
    <DetailDesc>This should be fun - we"ll explore some of the really cool stuff, like ASP.NET server controls and Web Services.</DetailDesc>
    <EventDate>2002/07/17</EventDate>
    <StartTime>8:00AM</StartTime>
    <EndTime>4:30PM</EndTime>
  </Event>
  <Event>
    <ShortDesc>Writing Workshop for Musical Project with Gregg</ShortDesc>
    <DetailDesc>We"re going to brainstorm some ideas and see if we can come up with something great.  We"re off to a good start.</DetailDesc>
    <EventDate>2002/07/19</EventDate>
    <StartTime>10:00AM</StartTime>
    <EndTime>6:30PM</EndTime>
  </Event>
  <Event>
    <ShortDesc>Community Band</ShortDesc>
    <DetailDesc>Central park - we"ll play everything from standards to shows tunes to classical to marches - you name it.  People bring their lawn chairs, eat their dinner, kids play - a great time!</DetailDesc>
    <EventDate>2002/07/24</EventDate>
    <StartTime>7:00PM</StartTime>
    <EndTime>9:00PM</EndTime>
  </Event>
  <Event>
    <ShortDesc>Jam Session at the Beach</ShortDesc>
    <DetailDesc>Bring more food this time and the crab nets - and the instruments!  We"ll might stay for a week or so depending on the weather.</DetailDesc>
    <EventDate>2002/07/21</EventDate>
    <StartTime>8:00AM</StartTime>
    <EndTime>11:30PM</EndTime>
  </Event>
  <Event>
    <ShortDesc>Rob"s Birthday!</ShortDesc>
    <DetailDesc>Nothing too fancy - just friends and family.  Hope it"s a nice day - bike ride would be fun.</DetailDesc>
    <EventDate>2002/07/30</EventDate>
    <StartTime>6:09PM</StartTime>
    <EndTime>11:30PM</EndTime>
  </Event>
  <Event>
    <ShortDesc />
    <DetailDesc />
    <EventDate />
    <StartTime />
    <EndTime />
  </Event>
  <Event>
    <ShortDesc>Event</ShortDesc>
    <DetailDesc>Number </DetailDesc>
    <EventDate>Wrox</EventDate>
    <StartTime>6.00</StartTime>
    <EndTime>11.30</EndTime>
  </Event>
</MyCalendar>
--%>