繁体   English   中英

当前索引超出范围c#

[英]the current index is out of range c#

我有下面的C#代码,我正在得到当前索引超出范围错误

 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; }
  }

我得到的错误在以下部分中,即“当前索引超出范围”

foreach (XmlNode noeud in listeNode){

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

你能帮我么

谢谢

问题:您可能正在访问Pays.xml文件的invalid属性。
解决方案:在访问Pays.xml文件的Attributes.Count之前,您需要检查Attributes.Count属性。

尝试这个:

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;
 }


}

该错误是由于您使用的索引超出范围。

例如,如果数组大小为3,但是如果您尝试访问第4个索引,它将给出错误。

所以请检查这部分的索引值

foreach (XmlNode noeud in listeNode){

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

问题出在Attributes []索引之一中。 您得到第2、3和4位,我敢打赌,您没有那么多的属性(4、3或2)。

您可以先将这些值设置为某些变量,然后再使用它们。

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

但这不是一个很好的做法。...您将首先检查该属性是否存在。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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