【问题标题】:DataBinding XML - Cannot bind to datasourceDataBinding XML - 无法绑定到数据源
【发布时间】:2018-08-16 16:28:50
【问题描述】:

我正在使用 XML 测试非常简单的 DataBinding,当 XML 的 ChildNode 深度超过 2 级时,我遇到了麻烦。

我收到此错误:

System.ArgumentException: '无法绑定到属性或列 数据源上的 SecondLevel/SecondNode1。参数名称:dataMember'

我没有使用 XSD 架构文件,但如果有帮助,我这样做不是问题。

这是我的 XML 内容:

<?xml version="1.0" encoding="UTF-8"?>
<sample xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<MainNode>
    <SubNode1>basic string</SubNode1>
    <SubNode2>0</SubNode2>
    <SubNode3>true</SubNode3>
    <SecondLevel>
        <SecondNode1>another string</SecondNode1>
        <SecondNode2>1</SecondNode2>
        <SecondNode3>false</SecondNode3>
    </SecondLevel>
</MainNode>
</sample>

这是我的 C# 代码:

public Form1()
{
    InitializeComponent();

    // load the file
    DataSet ds = new DataSet();
    ds.ReadXml("sample.xml");

    BindingSource bs = new BindingSource();

    //bs.DataSource = ds;
    //bs.DataMember = ds.Tables[0].TableName; //main node
    bs.DataSource = ds.Tables[0];
    //bs.DataMember = ds.Tables[0].TableName; //main node

    textBox1.DataBindings.Add("Text", bs, "SubNode1");
    comboBox1.DataBindings.Add("SelectedIndex", bs, "SubNode2");
    checkBox1.DataBindings.Add("Checked", bs, "SubNode3");

    //Error happens below
    textBox2.DataBindings.Add("Text", bs, "SecondLevel/SecondNode1");
    //comboBox2.DataBindings.Add("SelectedIndex", bs, "SecondLevel/SecondNode2");
    //checkBox2.DataBindings.Add("Checked", bs, "SecondLevel/SecondNode3");
}

另外,如果你能给我指出一种方法来实现这两种方式,那会有所帮助! 谢谢。

【问题讨论】:

  • 使用 DataSource ReadXml 方法时,第一个标签是数据集名称。第二级标记是 DataTable 名称。第三层是列名。第四层是行数据。当您有超过 4 层时,ReadXml 层会创建一堆无法重组或使用的断裂表。所以最好创建一个自定义的 xml 解析器,以将数据放入可用的格式。在您的情况下,看起来数据正在被放入第 4 个表中所以请使用 ds.Tables[3]。
  • @jdweng 我刚刚尝试使用 ds.Tables[4] = 错误找不到表 3。尝试过 [4],同样的事情 - 找不到...
  • 你是对的。 sample 是数据集名称,MainNode 是唯一的表。

标签: c# xml data-binding


【解决方案1】:

好的,我想通了。

这是修改后的代码 - 基本上,我删除了 BindingSource, 并直接使用了 DataSet (Duh!)

public Form1()
{
    InitializeComponent();

    // load the file
    DataSet ds = new DataSet();
    ds.ReadXml("sample.xml");

    // Removed usage of BindingSource
    // BindingSource bs = new BindingSource();
    // bs.DataSource = ds.Tables[0];

    textBox1.DataBindings.Add("Text", ds.Tables[0], "SubNode1");
    comboBox1.DataBindings.Add("SelectedIndex", ds.Tables[0], "SubNode2");
    checkBox1.DataBindings.Add("Checked", ds.Tables[0], "SubNode3");

    // Error fixed when using ds directly
    textBox2.DataBindings.Add("Text", ds.Tables[1], "SecondNode1");
    comboBox2.DataBindings.Add("SelectedIndex", ds.Tables[1], "SecondNode2");
    checkBox2.DataBindings.Add("Checked", ds.Tables[1], "SecondNode3");
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-23
    • 2012-09-02
    • 1970-01-01
    • 2011-03-07
    • 2015-08-16
    • 2018-10-22
    相关资源
    最近更新 更多