2011-05-03 10 views

Respuesta

4

Tendrá que leer los datos del archivo y puede usar algo como dataset.ReadXML() y luego usarlo para establecer su enlace para su cuadro combinado.

Aquí hay un ejemplo para comenzar. http://www.codeproject.com/KB/cs/dropdownfromxml.aspx

Actualización: Tenga en cuenta que hay dos clases de DataGrid. El que tiene el método DataBind() está en el espacio de nombres System.Web.UI.WebControls. El control de formulario de Windows no tiene el método DataBind y debería funcionar sin esa línea. Ver: http://msdn.microsoft.com/en-us/library/system.windows.forms.datagrid.datasource.aspx

+0

vi el ejemplo de este vínculo, pero estoy consiguiendo error en datagrid.databind última línea(); y cnt averigüe el error – anasooya

+0

¿Puede publicar el error que está obteniendo utilizando el ejemplo del enlace? – KaeL

+0

'System.Windows.Forms.DataGrid no contiene una definición para' DataBind 'y no se pudo encontrar ningún método de extensión' DataBind 'que aceptara un primer argumento de tipo' System.Windows.Forms.DataBind '(¿falta una directiva using? ¿o una referencia de ensamblaje?) – anasooya

7

Usando la clase XmlDocument puede recorrer los nodos del archivo xml y luego seguir añadiendo elementos a la lista desplegable. código de la muestra:

XmlDocument doc = new XmlDocument(); 
    doc.Load(Server.MapPath("regis.xml")); 
    XmlNodeList colorList = doc.SelectNodes("Information/Comments/Name"); 
    foreach (XmlNode Name in colorList) 
    { 
     DropDownList1.Items.Add(Name.InnerText); 
    } 

Ref: http://r4r.co.in/asp.net/01/tutorial/asp.net/How%20to%20populate%20combobox%20from%20xml%20file%20using%20c-Sharp%20in%20asp.net.shtml

+0

¿Será el mismo código aplicable para la aplicación de formulario de Windows – anasooya

+0

no realmente ... No soy un desarrollador de formulario ganador, pero supongo que la lógica debería ser más o menos la misma. Looping a través del archivo y luego agregar al cuadro combinado. Haz alguna búsqueda en Google – pramodtech

+0

ok lo tengo, pero mi archivo xml es un poco complicado, no estoy siendo capaz de entender cómo seleccionar los nodos, como en el código que ha enviado. – anasooya

2

Teniendo en cuenta este XML

<?xml version="1.0" encoding="UTF-8"?> 
<root> 
    <node1 attribute1="attrib1" attribute2="attrib2"> 
     <node2> 
      <node3>Item1</node3> 
      <node3>Item2</node3> 
      <node3>Item3</node3> 
     </node2> 
    </node1> 
</root> 

Podemos llegar a los datos de algunas maneras. Esta clase tiene dos métodos, el primero recorrerá todos los nodos hasta que llegue a los datos que queremos. El segundo usará el método XmlDocument.GetElementsByTagName() para ir directamente a los datos que queremos.

using System; 
using System.Xml; 
using System.Collections.Generic; 

public static class MyXmlParser 
{ 
    ///This method will loop through each node to get to the data we want. 
    public static List<string> GetItemsFromXmlByLoopingThroughEachNode(string Filename) 
    { 
     //Create a list to store all the items. 
     List<string> Items = new List<string>(); 

     //Load the document from a file. 
     XmlDocument doc = new XmlDocument(); 
     doc.Load(Filename); 

     //Loop through all the nodes in the document. 
     foreach(XmlNode RootNode in doc.ChildNodes) 
     { 
      if(RootNode.NodeType != XmlNodeType.XmlDeclaration) 
      {//If the node is not the declaration node parse it. 

       //Loop through all the child nodes of <root> 
       foreach(XmlNode Node1Node in RootNode.ChildNodes) 
       { 
        //Read Attributes of <node1> 
        XmlAttributeCollection attributes = Node1Node.Attributes; 
        XmlAttribute Attribute1 = attributes["attribute1"]; 
        //Attribute1.Value will give you the string contained in the attribute. 

        //Loop through all child nodes of <node1> 
        foreach(XmlNode Node2Node in Node1Node.ChildNodes) 
        { 
         //Loop through all child nodes of <node2> 
         foreach(XmlNode Node3Node in Node2Node.ChildNodes) 
         { 
          //These nodes contain the data we want so lets add it to our List. 
          Items.Add(Node3Node.InnerText); 
         } 
        } 
       }   
      } 
     } 
     //Return the List of items we found. 
     return Items; 
    } 

    ///This method will use GetElementsByTagName to go right to the data we want. 
    public static List<string> GetItemsFromXmlUsingTagNames(string Filename, string TagName) 
    { 
     //Create a list to store all the items. 
     List<string> Items = new List<string>(); 

     //Load the document from a file. 
     XmlDocument doc = new XmlDocument(); 
     doc.Load(Filename); 

     //Get all the <node3> nodes. 
     XmlNodeList Node3Nodes = doc.GetElementsByTagName(TagName); 
     //Loop through the node list to get the data we want. 
     foreach(XmlNode Node3Node in Node3Nodes) 
     { 
      //These nodes contain the data we want so lets add it to our List. 
      Items.Add(Node3Node.InnerText); 
     } 
     //Return the List of items we found. 
     return Items;  
    } 
} 

Una vez que tenga los datos que necesita, puede agregar los elementos a la ComboBox

//Get the items from the XML file. 
List<string> Items = MyXmlParser.GetItemsFromXmlUsingTagNames("C:\\test.xml","node3"); 
//Add them to the ComboBox 
ComboBox1.Items.AddRange(Items.ToArray()) 

Ver

XmlDocument

XmlNodeList

XmlNode

XmlAttributeCollection

XmlAttribute

Cuestiones relacionadas