我一直在尝试在两个单独的Combobox中填充xml文件中的某些值。第二个组合框的内容取决于第一个组合框的选择。第一个组合框将包含“ ClusterName ”&第二个将包含相应的“ MachineID ”
我已填充了clustername组合框,但我无法填充相应的machineid。
The C# code I used to populate the the first combobox:
public void PopulateClusterNameDropDown()
{
XDocument doc = XDocument.Load("the path of the file");
List<string> clusterNameList = doc.Root
.Elements("Machines")
.Elements("Cluster")
.Elements("ClusterName")
.Select(x => (string)x)
.ToList();
BindingSource bs = new BindingSource();
bs.DataSource = clusterNameList;
cbSelectCluster.DataSource = bs;
}
编辑:
我尝试填充Machineid组合框的代码
private void cbSelectCluster_SelectedIndexChanged(object sender, EventArgs e)
{
XElement root = XElement.Load("file path");
if (!cbSelectCluster.Text.Trim().Equals("")) {
cbSelectMachineID.Enabled = true;
cbSelectMachineID.Items.Clear();
var selected = from cli in root.Elements("Machines").Elements("Cluster").Elements("MachineID")
where cli.Element("ClusterName").Value.Equals(cbSelectCluster.Text)
select cli;
BindingSource bs = new BindingSource();
bs.DataSource = selected;
cbSelectMachineID.DataSource = bs;
}
}
Xml如下
<Config>
<Machines>
<Cluster>
<ClusterName>ABC</ClusterName>
<MachineID>Machine123</MachineID>
<MachineID>Machine456</MachineID>
<MachineID>Machine789</MachineID>
</Cluster>
<Cluster>
<ClusterName>XYZ</ClusterName>
<MachineID>Machine111</MachineID>
<MachineID>Machine222</MachineID>
<MachineID>Machine333</MachineID>
</Cluster>
</Machines>
</Config>
答案 0 :(得分:1)
您遇到此问题是因为您正在寻找MachineID元素下的ClusterName元素。 您只需要修复LINQ。
请在下面找到固定的代码。
此外,值得注意的是我已删除了cbSelectMachineID.Items.Clear()行,因为如果设置了数据源,则无法清除组合框。
try {
do {
System.out.println("\nEnter a numerator:\n");
int num1 = div.nextInt();
System.out.println("Enter a denominator:");
int num2 = div.nextInt();
int result = quotient(num1, num2);
System.out.printf("The Answer is: %d / %d = %d%n", num1, num2, result);
} while (continueLoop);
} catch (ArithmeticException arithmeticException) {
System.err.printf("\n Exception \n", arithmeticException);
System.out.printf(" Zero is an invalid entry");
} catch (InputMissMatchException inputMismatchException) {
System.err.printf("\n Exception \n", inputMismatchException);
div.nextLine();
System.out.printf("You must enter integers");
}
System.out.printf("\n GOODBYE \n");
希望这有帮助。