C# 数据绑定XML-无法绑定到数据源
我正在用XML测试非常简单的数据绑定,当XML的子节点深度超过2级时,我会遇到问题 我得到这个错误: System.ArgumentException:'无法绑定到属性或列 数据源上的SecondLevel/SecondNode1。参数名称:dataMember' 我没有使用和XSD模式文件,但如果有帮助的话,这样做对我来说不是问题 这是我的XML内容:C# 数据绑定XML-无法绑定到数据源,c#,xml,data-binding,C#,Xml,Data Binding,我正在用XML测试非常简单的数据绑定,当XML的子节点深度超过2级时,我会遇到问题 我得到这个错误: System.ArgumentException:'无法绑定到属性或列 数据源上的SecondLevel/SecondNode1。参数名称:dataMember' 我没有使用和XSD模式文件,但如果有帮助的话,这样做对我来说不是问题 这是我的XML内容: <?xml version="1.0" encoding="UTF-8"?> <sample xmlns:xsi="http
<?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>
另外,如果你能给我指出一个双向的方法,那会有帮助的!
谢谢。好的,我知道了
这是经过修改的代码,基本上,我删除了BindingSource,
并直接使用数据集(Duh!)
使用DataSource ReadXml方法时,第一个标记是数据集名称。第二级标记是DataTable名称。第三层是列名。第四层是行数据。当您有4个以上的层时,ReadXml层将创建一组无法重新组合或使用的断开表。因此,最好创建一个自定义xml解析器,将数据转换成可用的格式。在您的情况下,数据似乎被放入第4个表中,因此请使用ds.Tables[3]。@jdweng我刚刚尝试使用ds.Tables[4]=错误无法找到表3。尝试过[4],同样的事情-找不到…你是对的。sample是数据集名称,MainNode是唯一的表。
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");
}
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");
}