你提供的代码行不正确。 Value Members
of the combo Box should be set to the ,name of the property or栏, whichyou to be the of their selected Object (unique ID for example). 但是,你正在填满一个领域内容的“密码>。
When you bind the combo box in this way (setting the datasource with combination of DisplayMember
and ValueMember
), the SelectedValue
property of the combo box is filled with the value of ValueMember
field of the selected row.
例如,假定你有一栏数据:ActorID,Name和BirthDate,其中有一些数据:
DataTable dt = new DataTable();
dt.Columns.Add("ActorID", typeof(int));
dt.Columns.Add("Name", typeof(string));
dt.Columns.Add("BirthDate", typeof(DateTime));
dt.Rows.Add(1, "Will Smith", new DateTime(1968,9,25));
dt.Rows.Add(2, "Bruce Willis", new DateTime(1955,3,19));
dt.Rows.Add(3, "Jim Carrey", new DateTime(1962, 1, 17));
dt.Rows.Add(18, "Nicole Kidman", new DateTime(1967,6,20));
ComboBox cb = new ComboBox();
cb.DropDownStyle = ComboBoxStyle.DropDownList;
cb.Location = new Point(20, 100);
cb.Width = 100;
cb.DisplayMember = "Name"; // *****
cb.ValueMember = "ActorID"; // ***** The important part
cb.DataSource = dt;
Button btn = new Button();
btn.Text = "Show ID";
btn.Location = new Point(10, 140);
btn.Click += (sender, e) =>
{
MessageBox.Show(cb.SelectedValue.ToString()); // **** The other important part.
};
Form f = new Form();
f.Controls.Add(cb);
f.Controls.Add(btn);
f.ShowDialog();
当我们读到 com子的<代码>S selectedValue时,它使我们获得了选定行的“ActorID”。