【问题标题】:Attempting to build a DataGridView from Xml. Not working尝试从 Xml 构建 DataGridView。不工作
【发布时间】:2011-03-13 16:02:39
【问题描述】:

代码如下:

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;

我的 XML 文件如下所示:

好吧,我不知道如何正确转义 XML,但是有一个名为 Account 的元素带有 AccountType,内部文本为 Email Accounts,或 Web Accounts 或与项目匹配的类似内容在组合框中。此外还有其他子元素,例如用户名、密码等。

问题是当代码实际执行时,DataGridView 填充了正确的行和列,但其中没有任何内容....我做错了什么?

【问题讨论】:

    标签: c# xml dataset


    【解决方案1】:

    分配数据源后,您需要调用databind()。

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

    您还应该能够直接绑定到XML。像这样的...

    DataSet ds = new DataSet();
    ds.ReadXml("passfile.xml",XmlReadMode.InferSchema);
    dataGridView1.DataSource = ds;
    dataGridView1.DataBind();
    

    【讨论】:

    • hmm似乎工作。 IntelliSense似乎找不到DataBind()方法。我正在使用C#4.0与Visual C#Express 2010. Google搜索带来了这个....绑定源bsource = new bindingsource(); bsource.datasource = DS; DataGridView1.DataSource = Bsource;我试过但仍然没有工作。我忘记了使用陈述吗?我使用错误的数据源吗? span>
    • 什么类型的控制是DataGridView1?如果它是GridView,它应该具有DataBind()方法。 msdn.microsoft.com/en-us/library/fkx0cy6d.aspx。您没有指定是否这是ASP.NET,Silverlight,Windows窗体或WPF - 知道这将有所帮助。 span>
    • 抱歉延迟响应。这是一个Windows窗体应用程序,控制类型是DataGridView ....我只是将其吸入来自设计师的形式。它似乎没有数据介绍()方法。 IntelliSense显示数据绑定....和数据绑定操作。引用我的其他问题....将在将节点添加到XML文件时,执行此绑定启用GridView以自动更新? span>
    • 我之前没有使用dataGridview - 你是对的,它没有数据项()方法。这是另一个问题,询问将DataGridView直接绑定到XML。 stackoverflow.com/questions/265604/…
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-25
    • 2015-06-23
    • 1970-01-01
    • 2020-11-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多