Domanda

  1. The xml file is error free
  2. The drink class is marked public
  3. I have tried to run the form without the drink array and just add the button array to the form and get the same error.
  4. My ultimate goal is to add the text from the productName element in the xml file to the buttons.

    private void Form1_Load(object sender, EventArgs e)
    {
    
        TextReader stream = null;
    
        try
        {
            //Deserialize XML from drink.xml file
    
            XmlSerializer serializer = new XmlSerializer(typeof(drink[])); 
            stream = new StreamReader("XML/drinks.xml");
            drink[] drinks = (drink[])serializer.Deserialize(stream);
    
            Button[] btnArray = new Button[drinks.Length];
    
    
            for (int x = 0; x < drinks.Length; x++)//add to form
            {
                this.Controls.Add(btnArray[x]);
                btnArray[x].Text = drinks[x].productName;
            }
        }
    
        catch (XmlException ex)
        {
            MessageBox.Show(ex.Message, "XML Parse Error",
            MessageBoxButtons.OK, MessageBoxIcon.Error);
    
        }
        catch (InvalidOperationException ioe)
        {
            MessageBox.Show(ioe.ToString(ioe));
        }
        catch (Exception e1)
        {
            MessageBox.Show(Convert.ToString(e1));
        }
        finally
        {
            stream.Close();
    
        }
    
    
    
    }
    
È stato utile?

Soluzione

Button[] btnArray = new Button[drinks.Length];

You have only created an array holding Buttons, but you haven't create individual Button instances.

You have to create the actual Button before adding them to the Controls and change their properties, something like:

for (int x = 0; x < drinks.Length; x++)//add to form
{
    btnArray[x] = new Button { Text = drinks[x].productName };
    this.Controls.Add(btnArray[x]);
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top