tags:

views:

31

answers:

1

Code is as follows:

        string fileName = "passfile.xml";
        DataSet ds = new DataSet("Account List");
        DataTable accounts = ds.Tables.Add("Accounts");

        accounts.Columns.AddRange(new DataColumn[] {
            new DataColumn("Username"),
            new DataColumn("Password"),
            new DataColumn("Description")});

        XmlDocument doc = new XmlDocument();
        doc.Load(fileName);
        foreach (XmlNode node in doc.GetElementsByTagName(accountGroupsBox.SelectedItem.ToString()))
        {
            DataRow row = accounts.Rows.Add(
                node["Username"].InnerText,
                node["Password"].InnerText,
                node["Description"].InnerText);
        }
        dataGridView1.DataSource = accounts;

My XML File looks like this:

Well I couldnt figure out how to properly escape the XML, But there there is an element called Account with AccountType with inner text as Email Accounts, or Web Accounts or something similar that matches the items in the combo box. Addtionally there are other child elements such as Username, Password, ect.

The problem is when the code actually executes, the DataGridView fills with the proper rows and coulums, but where is nothing in them....what did I do wrong?

A: 

After you assign your DataSource, you need to call DataBind().

dataGridView1.DataSource = accounts;
dataGridView1.DataBind();

You should also be able to bind directly to the XML. Something like this...

DataSet ds = new DataSet();
ds.ReadXml("passfile.xml",XmlReadMode.InferSchema);
dataGridView1.DataSource = ds;
dataGridView1.DataBind();
Jason
Hmm that doesnt seem to work. Intellisense cant seem to find a DataBind() method. I'm using C# 4.0 with Visual C# Express 2010. A google search brought up this....Bindingsource bSource = new BindingSource();bSource.DataSource = ds;dataGridView1.DataSource = bSource;I tried that but still didn't work. Did I forget a using statement? Am I using the wrong data source?
Stev0
What type of control is dataGridView1? If it's a GridView, it should have a DataBind() method. http://msdn.microsoft.com/en-us/library/fkx0cy6d.aspx. You don't specify if this is ASP.NET, SilverLight, Windows Forms, or WPF - knowing that would help.
Jason
Sorry for the delayed response. This is a windows forms application, and the control type is dataGridView....I just drug it into the form from the designer. It doesnt appear to have a DataBind() method. Intellisense shows a DataBindings....and a DataBindingComplete. Referencing my other question....will doing this binding enable the gridview to update automatically when a node is added to the xml file?
Stev0
I haven't used DataGridView before - you're right that it doesn't have a DataBind() method. Here's another question that asks about binding DataGridView directly to XML. http://stackoverflow.com/questions/265604/how-do-i-use-xml-as-a-datasource-for-a-datagridview-in-a-winforms-project
Jason