我面临重复名称异常

时间:2016-06-07 06:41:35

标签: c# telerik-grid

这是.aspx.cs文件。

using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Xml.Linq;
using System.Linq;
using Telerik.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI;
//using System.Web.UI.Control;
using System.Web;
using System.Web.Util;
using System.Xml;
using System.Windows.Forms;


namespace Grid.Examples.DataEditing.XmlDataSourse
{
public partial class Default : System.Web.UI.Page
{
    private const string BACKUP_PATH = "~/App_Data/Xml/NewBuyerLoginRef.xml";
    private const string FILE_PATH = "~/App_Data/Xml/NewBuyerLogin.xml";
    private const int MAX_LENGTH = 25;

    /// <summary>
    /// Tracks how many times the page was requested.
    /// </summary>
    public int TimesRequested
    {
        get
        {
            if (this.Application["requested"] == null)
            {
                this.Application["requested"] = 0;
            }
            return (int)this.Application["requested"];
        }
        set
        {
            this.Application["requested"] = value;
        }
    }

    /*  protected void Page_Load(object sender, EventArgs e)
      {
          TimesRequested++;
          if (TimesRequested >= 3)
          {
              //If the page is requested more than three times, refresh the XML file...
              TimesRequested = 0;
            RefreshXmlFile(BACKUP_PATH, FILE_PATH);
          }
      }*/

    protected void RadGrid2_NeedDataSource(object sender, GridNeedDataSourceEventArgs e)
    {
       var sourceDocument = LoadDocument(FILE_PATH);
        //var customers = GetCustomersEnumeration(sourceDocument, "Customers", "Customer");
       // var customers = from field in sourceDocument.Descendants() select field;


        var x = sourceDocument.Descendants("tasks");
        var y = x.Descendants("fillPage");
        var z= y.Descendants("input");
        var w=z.Descendants("fields");
      // XmlNodeList nodes= sourceDocument.selectNodes
     //  IEnumerable<XNode> nodes = sourceDocument.NodesAfterSelf().Single(XElement.Equals(Attribute("seq").Value,"3" )).FirstOrDefault;
        var gridSource = (from field in w.Descendants()
                          select new { id = field.Attribute("id").Value, email = field.Attribute("email").Value, login_passowrd = field.Attribute("login_password").Value });
        (sender as RadGrid).DataSource = gridSource;

        //Rebind the upper Grid so the changes are reflected
        this.RadGrid1.Rebind();
    }

    protected void RadGrid2_UpdateCommand(object source, GridCommandEventArgs e)
    {
        GridEditFormItem editForm = (GridEditFormItem)e.Item;
        Hashtable newValues = new Hashtable();

        //Extract the new values from the editor controls
        editForm.ExtractValues(newValues);

        //Get the "Primary key" value that will be used to perform CRUD operations
        string id = editForm.GetDataKeyValue("id").ToString();

        //Load the XML document in memory...
        var sourceDocument = LoadDocument(FILE_PATH);
        var x = sourceDocument.Descendants("tasks");
        var y = x.Descendants("fillPage");
        var z = y.Descendants("input");
        var w = z.Descendants("fields");

        //Get IEnumerable of the Customer elements
     //   var customers = GetCustomersEnumeration(sourceDocument, "Customers", "Customer");

        //Get a reference to the modified record
        XElement affectedElement = (from field in z.Descendants()
                                    where field.Attribute("id").Value == id
                                    select field).FirstOrDefault();


        //Validate and update the input strings
        foreach (DictionaryEntry entry in newValues)
        {
            affectedElement.Attribute(entry.Key.ToString()).Value = ValidateString(entry.Key.ToString(), entry);
        }

        //Save the new values to the document
        SaveChanges(sourceDocument, FILE_PATH);
    }

    protected void RadGrid2_InsertCommand(object source, GridCommandEventArgs e)
    {
        GridEditFormItem editForm = (GridEditFormItem)e.Item;
        Hashtable newValues = new Hashtable();

        //Extract the new values from the editor controls
        editForm.ExtractValues(newValues);

        //Load the XML document in memory...
        var sourceDocument = LoadDocument(FILE_PATH);
        var x = sourceDocument.Descendants();
        var y = x.Descendants("fillPage");
        var z = y.Descendants("input");
        var w = z.Descendants("fields");

        //Get IEnumerable of the Customer elements
      //  var customers = GetCustomersEnumeration(sourceDocument, "Customers", "Customer");
        XElement root = (from fields in z
                         select fields).LastOrDefault();
        // int x = 1;
        //Construct the new "Primary key"
        string lastid = root.Attribute("id").Value;
        int a = 1 + Int32.Parse(lastid);
        //Add the "Primary key" to the attributes values that will be used to construct the new element
        newValues.Add("id", a);


        //Construct the new element that will be inserted
        XElement element = new XElement("field");

        //Validate and add the input strings
        foreach (DictionaryEntry entry in newValues)
        {
            XAttribute attribute = new XAttribute(entry.Key.ToString(), ValidateString(entry.Key.ToString(), entry));
            //Add the supplied values as attributes to the newly created element
            element.Add(attribute);
        }

        //Add the newly created element
        var b = sourceDocument.Descendants().Descendants("fillPage").Descendants("input").Descendants().LastOrDefault();
        b.Add(element);


        //Save the new values to the document
        SaveChanges(sourceDocument, FILE_PATH);
    }

    protected void RadGrid2_DeleteCommand(object source, GridCommandEventArgs e)
    {
        GridDataItem dataItem = (GridDataItem)e.Item;

        //Get the "Primary key" value that will be used to perform the Delete operation
        string customerID = dataItem.GetDataKeyValue("id").ToString();

        //Load the XML document in memory...
        XDocument sourceDocument = LoadDocument(FILE_PATH);
        var x = sourceDocument.Descendants("tasks");
        var y = x.Descendants("fillPage");
        var z = y.Descendants("input");
        var w = z.Descendants("fields");

        //Get IEnumerable of the Customer elements
       // var customers = GetCustomersEnumeration(sourceDocument, "Customers", "Customer");

        //Get the element that should be deleted
        XElement elelemntToDelete = (from field in w.Descendants()
                                     where field.Attribute("id").Value == customerID
                                     select field).FirstOrDefault();

        //Remove the element from the XML document
        elelemntToDelete.Remove();

        //Save the new values to the document
        SaveChanges(sourceDocument, FILE_PATH);
    }

    /// <summary>
    /// Load the source document
    /// </summary>
    /// <param name="path">Path to the source document</param>
    /// <returns>XDocument</returns>
    private XDocument LoadDocument(string path)
    {
        XDocument sourceDocument = XDocument.Load(this.Server.MapPath(path));
        return sourceDocument;
    }

    /// <summary>
    /// Save the changes to the specified document
    /// </summary>
    /// <param name="sourceDocument">Path where the document will be saved</param>
    /// <param name="path">Path to the file where the changes will be saved</param>
    private void SaveChanges(XDocument sourceDocument, string path)
    {
        try
        {
            //Save the changes back to the file
            sourceDocument.Save(this.Server.MapPath(path));
        }
        catch (Exception ex)
        {
            //Notify the user if exception is raised
            this.Notification1.Text = ex.Message;
            this.Notification1.Show();
        }
    }

    /// <summary>
    /// Refresh the source file if more than 5 changes are made
    /// </summary>
    /// <param name="sourcePath">Path to the source file that will be used for the copy operation</param>
    /// <param name="targetPath">Path to the file that needs to be refreshed</param>
    private void RefreshXmlFile(string sourcePath, string targetPath)
    {
        try
        {
            File.Copy(
                this.Server.MapPath(sourcePath),
                this.Server.MapPath(targetPath),
                true);
        }
        catch (IOException ex)
        {
            this.Trace.Write(ex.InnerException.Message);
            this.Notification1.Text = ex.InnerException.Message;
            this.Notification1.Show();
        }

        Notification1.Text = "The xml data file was refreshed!";
        Notification1.Show();
    }

    /// <summary>
    ///    Get all the customers elements from the file
    /// </summary>
    /// <param name="sourceDocument">File that will be traversed</param>
    /// <param name="rootNode">Root node of the document</param>
    /// <param name="childNode">Child nodes that will be taken</param>
    /// <returns>IEnumerable</returns>
/*    private IEnumerable<XElement> GetCustomersEnumeration(XDocument sourceDocument, XName rootNode, XName childNode,XName schild,XName sschild)
    {
     var customers = sourceDocument.getElementById ;
        return customers;
    }*/

    /// <summary>
    /// Validates the input string before it is saved to the file
    /// </summary>
    /// <param name="attribute">The attribute to which the value should be saved</param>
    /// <param name="entry">DictionaryEntry that stores the input value</param>
    /// <returns>String</returns>
    private string ValidateString(string attribute, DictionaryEntry entry)
    {
        int strLength = this.ConvertNullToEmpty(entry.Value.ToString()).Length;

        //Split the string if it is too long
        if (strLength > MAX_LENGTH)
        {
            return HttpUtility.HtmlEncode(this.ConvertNullToEmpty(entry.Value).Substring(0, MAX_LENGTH));
        }
        else
        {
            return HttpUtility.HtmlEncode(this.ConvertNullToEmpty(entry.Value).Substring(0, strLength));
        }

    }

    /// <summary>
    /// Converts null value to empty string
    /// </summary>
    /// <param name="obj">Object that will be converted</param>
    /// <returns>String</returns>
    private String ConvertNullToEmpty(Object obj)
    {
        if (obj == null)
        {
            return String.Empty;
        }
        else
        {
            return obj.ToString();
        }
    }


}
}

这是数据源,即xml文件

<?xml version="1.0" encoding="utf-8"?>
<tasks xmlns="http://xxxxxx.com/systemic/testflow"         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xxxxxx.com/systemic/testflow ../../testflow.xsd">
 <!-- Seller Login -->
 <loadPage seq="1" deleteCookies="true">
 <taskName>Load login</taskName>
 <location url="/cgi-bin/webscr?cmd=_login-run" relative="true" />
 </loadPage>

 <clickElement seq="2" optional="true">
 <taskName>Click LogIn Button</taskName>
 <input>
   <fields>
    <field id="login-button" waitInSecs="5"/>
  </fields>
 </input>
 </clickElement>

 <fillPage seq="3">
 <taskName>FillLogin</taskName>
 <input>
    <fields>
    <field id="1" email="guestEmail" login_password="allxo123!"/>
    <field id="3" email="guestEmail3" login_password="allxo123!3"/>
    <field id="2" email="guestEmail2" login_password="allxo123!2"/>
  </fields>
 </input>
 </fillPage>

 <clickElement seq="4">
 <taskName>Login</taskName>
 <input>
   <fields>
    <field id="btnLogin" submit="true" submitWait="120"
                waitInSecs="25" />
  </fields>
  </input>
 </clickElement>

 </tasks>

错误消息显示

  

名为&#39; Value&#39;的列已经属于这个DataTable。

但是没有列名称&#39;值&#39;。在RadGrid2_UpdateCommand函数的第二行抛出异常。 我是新手。所以请帮忙。谢谢。

0 个答案:

没有答案