我在尝试获取我设置的ValueMember值时遇到了一些麻烦。我正在尝试使用组合框将XML数据读取到文本框。这是我的代码:
private void zamowienie_Load(object sender, EventArgs e)
{
label2.Text = DateTime.Now.ToShortDateString();
DataSet dsSet = new DataSet();
dsSet.ReadXml("E:\\baza\\spis_klientow.xml");
comboBox2.DataSource = dsSet.Tables["spis_klientow"];
comboBox2.DisplayMember = "ID";
comboBox2.ValueMember = "Name";
comboBox2.ValueMember = "Phone";
}
private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
{
DataSet ds = new DataSet();
ds.ReadXml("E:\\baza\\spis_klientow.xml");
foreach (DataRow item in ds.Tables["spis_klientow"].Rows)
{
label10.Text = item[1].ToString();
label11.Text = item[2].ToString();
}
}
答案 0 :(得分:0)
将DataTable
绑定为ComboBox
数据源时,ComboBox.Items
集合中会填充DataRowView
个对象。然后你可以像这样使用ComboBox.SelectedItem
private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
{
var source = (DataRowView)comboBox2.SelectedItem;
label10.Text = source["Name"].ToString();
label11.Text = source["Phone"].ToString();
// ...
}
但是,还有更好的方法。 WinForms数据绑定基础结构支持这种情况,而无需挂钩到具体的控件事件。您只需将组合框和文本框绑定到同一个数据源(在您的情况下为DataTable
)。
这是数据绑定的完整工作示例" magic"在行动:
using System;
using System.Data;
using System.Windows.Forms;
namespace Samples
{
static class Program
{
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
var form = new Form();
var comboBox = new ComboBox { Left = 16, Top = 16, DropDownStyle = ComboBoxStyle.DropDownList };
var textBoxID = new TextBox { Left = 16, Top = comboBox.Bottom + 8 };
var textBoxName = new TextBox { Left = 16, Top = textBoxID.Bottom + 8 };
var textBoxPhone = new TextBox { Left = 16, Top = textBoxName.Bottom + 8 };
form.Controls.AddRange(new Control[] { comboBox, textBoxID, textBoxName, textBoxPhone });
// Begin essential part
var dataSource = GetData();
textBoxID.DataBindings.Add("Text", dataSource, "ID");
textBoxName.DataBindings.Add("Text", dataSource, "Name");
textBoxPhone.DataBindings.Add("Text", dataSource, "Phone");
comboBox.DisplayMember = "Name";
comboBox.ValueMember = "ID";
comboBox.DataSource = dataSource;
// End essential part
Application.Run(form);
}
static DataTable GetData()
{
//DataSet dsSet = new DataSet();
//dsSet.ReadXml("E:\\baza\\spis_klientow.xml");
//return dsSet.Tables["spis_klientow"];
var table = new DataTable();
table.Columns.Add("ID", typeof(int));
table.Columns.Add("Name");
table.Columns.Add("Phone");
for (int i = 1; i <= 10; i++)
table.Rows.Add(i, "Name" + i, "Phone" + i);
return table;
}
}
}