简体   繁体   中英

the current index is out of range c#

I've the below c# code and i'm getting the current index is out of range error

 public partial class FrmTreeViewContinents : Form
 {
    // Objets communs
    XmlDocument monXml = new XmlDocument();
    XmlNodeList listeNode = null;
    XmlNode root = null;

    public FrmTreeViewContinents()
    {
        InitializeComponent();
    }

    private void btnTransferToXml_Click(object sender, EventArgs e)
    {
        ManipXml obj = new ManipXml();

        // Sérialise une collection d'objets 'Pays' en fichier XML
        obj.SerialiseObjets("Pays.xml");
    }

    private void btnAfficheEntity_Click(object sender, EventArgs e)
    {
        // Chargement du fichier XML - Abandon si erreur
        if (!ChargeFichierXml()) return;
        // Sélecton des données dans le noeud XML 'Pays'
        listeNode = root.SelectNodes("//Pays");
        // Affichage des données lues
        AffichageDonnees();
    }

    // Méthode d'affichage des données lues dans le fichier XML
    private void AffichageDonnees()
    {
        txtBoxAffiche.Clear();
        foreach (XmlNode noeud in listeNode)
        {
            txtBoxAffiche.Text += noeud.Attributes[2].InnerText.ToString() +
                " - " +
                noeud.Attributes[3].InnerText.ToString() +
                " - " +
                noeud.Attributes[4].InnerText.ToString() +
                Environment.NewLine;
        }
    }

    // Méthode de chargement du fichier XML
    private bool ChargeFichierXml()
    {
        try
        {
            monXml.Load("Pays.xml");
        }

        catch (Exception ex)
        {
         MessageBox.Show("Erreur sur chargement du fichier XML" 
         + Environment.NewLine + ex.Message,
                "Erreur",
                MessageBoxButtons.OK,
                MessageBoxIcon.Error);
            return false;
        }

        //XmlNodeList listeNode;
        root = monXml.DocumentElement;
        return true;
    }
  }

   class ManipXml
   {
    // Cette méthode permet de générer un fichier XML avec une collection de 'Pays'
    public void SerialiseObjets(string sNomFichierXml)
    {
        XmlSerializer xmlSerializer = new XmlSerializer(typeof(Collection<Pays>));

        Collection<Pays> colPays = new Collection<Pays>();

        Pays cnt1 = new Pays();
        cnt1.NomPays = "Australie";
        cnt1.NomCapitalePays = "Canberra";
        cnt1.NomContinent = "Australie";

        Pays cnt2 = new Pays();

        cnt2.NomPays = "France";
        cnt2.NomCapitalePays = "Paris";
        cnt2.NomContinent = "Europe";

        Pays cnt3 = new Pays();

        cnt3.NomPays = "Espagne";
        cnt3.NomCapitalePays = "Madrid";
        cnt3.NomContinent = "Europe";

        Pays cnt4 = new Pays();

        cnt4.NomPays = "Chine";
        cnt4.NomCapitalePays = "Beijing";
        cnt4.NomContinent = "Asie";

        Pays cnt5 = new Pays();

        cnt5.NomPays = "Malaysia";
        cnt5.NomCapitalePays = "Kuala-Lumpur";
        cnt5.NomContinent = "Asie";

        // Ajout des 'Continent' dans la collection
        colPays.Add(cnt1);
        colPays.Add(cnt2);
        colPays.Add(cnt3);
        colPays.Add(cnt4);
        colPays.Add(cnt5);

        // Instanciation d'un Stream
        Stream st = new FileStream(sNomFichierXml, FileMode.Create);
        // Génération du fichier XML
        xmlSerializer.Serialize(st, colPays);
        st.Close();
    }
  }
  public class Pays  // Définition de la classe Continent
  {
    public string NomPays { get; set; }
    public string NomCapitalePays { get; set; }
    public string NomContinent { get; set; }
  }

the error i got is in the section below , which is "the current index is out of range"

foreach (XmlNode noeud in listeNode){

 txtBoxAffiche.Text += noeud.Attributes[2].InnerText.ToString() +" - " 
 + noeud.Attributes[3].InnerText.ToString() + " - " 
 + noeud.Attributes[4].InnerText.ToString() +
       Environment.NewLine;
}

can you please help me

thank you

Problem : You might be accessing the invalid Attributes of the Pays.xml file.
Solution: You need to check the Attributes.Count property before accessing the Attributes of the Pays.xml file.

Try This:

foreach (XmlNode noeud in listeNode)
{

for(int i=2;i<noeud.Attributes.Count;i++)
{

if(i!=noeud.Attributes.Count-1)
     txtBoxAffiche.Text += noeud.Attributes[i].InnerText.ToString() +" - ";
else
     txtBoxAffiche.Text += noeud.Attributes[i].InnerText.ToString() + Environment.NewLine;
 }


}

The error is due to you are using the Index out of range.

for example if Array size 3 but if you try to access 4th index ,it will give error.

so please check this part for index value

foreach (XmlNode noeud in listeNode){

 txtBoxAffiche.Text += noeud.Attributes[2].InnerText.ToString() +" - " 
 + noeud.Attributes[3].InnerText.ToString() + " - " 
 + noeud.Attributes[4].InnerText.ToString() +
       Environment.NewLine;
}

The problem is in one of the Attributes[] index. You get the position 2, 3 and 4, and I bet that you don't have that many Attributes (4, 3 or 2).

You can set that values first to some variables before using them.

string attribute2 = noeud.Attributes[2].InnerText.ToString();
string attribute3 = noeud.Attributes[3].InnerText.ToString();
string attribute4 = noeud.Attributes[4].InnerText.ToString();

But this isn't a very good practice.... You would check first if the attribute exists.

string attribute2;
if (noeud.Attributes[2] != null) {
     attribute2 = noeud.Attributes[2].InnerText.ToString();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM