如何实现ComboBox选中ID后在Label展示对应Instructor的全部信息
问题描述
我有一个存储不同任务类型用户数据的XML文件,内容如下:
<Users> <Instructor> <ID>1</ID> <Name>Jack</Name> <Surname>C</Surname> <Rank>r1</Rank> </Instructor> <Instructor> <ID>2</ID> <Name>Jim</Name> <Surname>A</Surname> <Rank>r1</Rank> </Instructor> <Pilot> <ID>3</ID> <Name>Tim</Name> <Surname>T</Surname> <Rank>r2</Rank> </Pilot> </Users>
我已通过以下代码将Instructor的ID填充到comboBox1中:
void InsGetCombo() { DataSet ds = new DataSet(); ds.ReadXml(path); DataTable dt = ds.Tables["Instructor"]; comboBox1.DataSource = dt; comboBox1.DisplayMember = "ID"; }
需要实现的功能:在comboBox1中选中某个ID后,将该ID对应的Instructor的ID、Name、Surname、Rank信息显示在label1上。
我尝试通过指定ID字符串而非selectedIndex来获取Name,但未能成功,代码如下:
XmlDocument doc = new XmlDocument(); doc.Load(path); string id = "2"; label1.Text = doc.SelectSingleNode($"/Users/Instructor[ID='{id}']").Attributes["Name"].Value.ToString();
解决方案
你的核心错误是把Name当成了Instructor节点的属性,但实际上它是子节点,所以不能用Attributes["Name"]取值。另外,既然已经用DataSet绑定了数据源,直接从绑定的DataTable读取数据会更高效,无需重新加载XML文件。
方法一:利用已绑定的DataTable(推荐)
comboBox1的选中项对应DataRowView对象,可直接从中提取所有字段:
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e) { if (comboBox1.SelectedItem is DataRowView rowView) { string id = rowView["ID"].ToString(); string name = rowView["Name"].ToString(); string surname = rowView["Surname"].ToString(); string rank = rowView["Rank"].ToString(); label1.Text = $"ID: {id}, Name: {name}, Surname: {surname}, Rank: {rank}"; } }
方法二:修正XmlDocument查询代码
如果坚持使用XmlDocument,需修改子节点的获取方式:
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e) { if (comboBox1.SelectedItem == null) return; string selectedId = comboBox1.Text; XmlDocument doc = new XmlDocument(); doc.Load(path); XmlNode instructorNode = doc.SelectSingleNode($"/Users/Instructor[ID='{selectedId}']"); if (instructorNode != null) { string id = instructorNode.SelectSingleNode("ID").InnerText; string name = instructorNode.SelectSingleNode("Name").InnerText; string surname = instructorNode.SelectSingleNode("Surname").InnerText; string rank = instructorNode.SelectSingleNode("Rank").InnerText; label1.Text = $"ID: {id}, Name: {name}, Surname: {surname}, Rank: {rank}"; } }
注意事项
- 需确保
comboBox1已绑定SelectedIndexChanged事件,否则选中项变化时不会触发代码执行。
内容的提问来源于stack exchange,提问作者dositelu
相关产品推荐
相关产品推荐

