我对使用XML和datagridviews有点新意。我的问题是我有2个datagrids,我的第一个datagrid表也包含来自XML文件的以下数据。
empl_num | Name
1 | Carl
2 | Mark
3 | Tanner
另外,我有这个包含以下内容的XML文件:
<Address>
<Data1>
<employee>
<empl_num>1</empl_num>
<name>Carl</name>
<empl_num>2</empl_num>
<name>Mark</name>
<empl_num>3</empl_num>
<name>Tanner</name>
</employee>
</Data1>
<Data2>
<Person>
<EMPL_NUM>>100</EMPL_NUM>
<NAME>Carl</NAME>
<ID_NUM>1</ID_NUM>
<IsRequired>0</IsRequired>
</Person>
<Person>
<EMPL_NUM>200</EMPL_NUM>
<NAME>Mark</NAME>
<ID_NUM>2</ID_NUM>
<IsRequired>0</IsRequired>
</Person>
<Person>
<EMPL_NUM>300</EMPL_NUM>
<NAME>Tanner</NAME>
<ID_NUM>3</ID_NUM>
<IsRequired>0</IsRequired>
</Person>
</Data2>
</Address>
每当我从datagridview表中单击名称carl时,我可以问一下,它根据ID_NUM获取xml数据并将其显示到第二个datagridview表。(所需的输出如下所示)。
example:
- datagridview1- -datagridview2-
empl_num | Name EMPL_NUM | Name | ID_NUM | IsRequired
1 | Carl 100 | Carl | 1 | 0
2 | Mark
3 | Tanner
答案 0 :(得分:1)
通过绑定源与外键使用数据绑定。
// Fill data table (you should do it from xml file)
var dt1 = new DataTable("empl");
dt1.Columns.Add("empl_num");
dt1.Columns.Add("Name");
dt1.Rows.Add(1, "Carl");
dt1.Rows.Add(2, "Mark");
dt1.Rows.Add(3, "Tanner");
// Fill second data table
var dataSet = new DataSet();
using (var xmlReader = XmlReader.Create("test.xml"))
{
xmlReader.ReadToFollowing("Data2");
dataSet.ReadXml(xmlReader);
}
// Set a relation between two tables
dataSet.Tables.Add(dt1);
dataSet.Relations.Add("FK", dt1.Columns["empl_num"],
dataSet.Tables[0].Columns["ID_NUM"]);
var bs1 = new BindingSource();
bs1.DataSource = dataSet;
bs1.DataMember = "empl";
var bs2 = new BindingSource();
bs2.DataSource = bs1;
bs2.DataMember = "FK"; // note to foreign key
// Bind sources to grids
dataGridView1.DataSource = bs1;
dataGridView2.DataSource = bs2;