【发布时间】:2014-04-19 20:13:35
【问题描述】:
我有一个从DataTable 填充我的ComboBox 的方法:
public string populateCompanyTransSellingEntityLookUp(ref System.Windows.Forms.ComboBox Combo, string Id, Contract Contract)
{
SqlCommand _comm = new SqlCommand();
_comm.Parameters.AddWithValue("@id", Id);
_comm.CommandText = "SELECT [name] FROM dbo.fnGetList(@id) ORDER BY [name]; ";
_comm.Connection = _conn;
_comm.CommandTimeout = _command_timeout;
DataTable dt = new DataTable();
try
{
SqlDataReader myReader = _comm.ExecuteReader();
dt.Load(myReader);
Combo.DataSource = dt;
Combo.DisplayMember = "name";
foreach (DataRow dr in dt.Rows)
{
if (dr["name"].ToString() == Contract.Company_Name.ToString())
{
Combo.Text = dr["company_int_name"].ToString();
}
}
}
catch
{
MessageBox.Show("Unable to populate Company Name LookUp");
}
return "";
}
我将保存的值 Contract.Company_Name 传递到 forEach 循环中,以便从 DataTable 中找到我所需的 SelectedItem。 ComboBox 填充了来自 Combo.Datasource =dt; 的我的 DataTable 值,但未设置我的选定项目。代码编译无异常。如果我删除了Datasource = dt;, theSelectedItemis set no problem. Why is theDatasourceoverriding mySelectedItem`,我的绑定是否遗漏了什么?
谢谢大家
【问题讨论】:
-
像这样设置 ValueMember:Combo.ValueMember = "name";
-
不幸的是仍然没有修复...
标签: c# winforms combobox datatable