组合框从数据表Winforms C#中选择EdItem?
我的DAL中有一个方法,它从组合框从数据表Winforms C#中选择EdItem?,c#,winforms,combobox,datatable,C#,Winforms,Combobox,Datatable,我的DAL中有一个方法,它从数据表中填充组合框。组合框显示正确,我有一个'保存'按钮,它保存回我的数据库,工作是一个很好的'联合国 public string populateLookUp(ref System.Windows.Forms.ComboBox Combo, string Id) { SqlCommand _comm = new SqlCommand(); _comm.Parameters.AddWithValue("@id", Id);
数据表中填充组合框。组合框显示正确,我有一个'保存'按钮,它保存回我的数据库,工作是一个很好的'联合国
public string populateLookUp(ref System.Windows.Forms.ComboBox Combo, string Id)
{
SqlCommand _comm = new SqlCommand();
_comm.Parameters.AddWithValue("@id", Id);
_comm.CommandText = "SELECT [name] FROM dbo.fnGetName(@id) ORDER BY [name]; ";
_comm.Connection = _conn;
_comm.CommandTimeout = _command_timeout;
DataTable dt = new DataTable();
try
{
SqlDataReader myReader = _comm.ExecuteReader();
dt.Load(myReader);
}
catch
{
MessageBox.Show("Unable to populate Name LookUp");
}
Combo.DataSource = dt;
Combo.DisplayMember = "name";
foreach (DataRow dr in dt.Rows)
{
if (dr["company_int_name"].ToString() == Contract.Company_trans_Selling_Entity.ToString())
{
Combo.SelectedItem = dr["company_int_name"].ToString();
}
}
return "";
}
但是很明显,当我重新编辑记录时,会再次调用此方法。好的,我现在已经编写了一个ForEach
循环,它迭代我的数据表,并将行中的字符串与我传入的名称进行比较。如果两者匹配,我将设置
Combo.SeletedItem = dr["company_int_name"].ToString();
但是没有设置selectedItem
,我可能需要某种事件来通知属性已更改
谢谢您必须将组合框与ValueMember函数绑定,并且可以使用所选的匹配字符串值反映组合框
public string populateLookUp(ref System.Windows.Forms.ComboBox Combo, string Id)
{
SqlCommand _comm = new SqlCommand();
_comm.Parameters.AddWithValue("@id", Id);
_comm.CommandText = "SELECT [name] FROM dbo.fnGetName(@id) ORDER BY [name]; ";
_comm.Connection = _conn;
_comm.CommandTimeout = _command_timeout;
DataTable dt = new DataTable();
try
{
SqlDataReader myReader = _comm.ExecuteReader();
dt.Load(myReader);
}
catch
{
MessageBox.Show("Unable to populate Name LookUp");
}
Combo.DataSource = dt;
Combo.DisplayMember = "name";
Combo.ValueMember = "name";
foreach (DataRow dr in dt.Rows)
{
if (dr["company_int_name"].ToString() == Contract.Company_trans_Selling_Entity.ToString())
{
Combo.SelectedValue = dr["company_int_name"].ToString();
}
}
return "";
}
保存记录时,是否存储组合框中选定的值?是的,我有一个保存方法,该方法传递值。此值被传递到sql INSERT语句中。请尝试使用Combobox的text属性,如下所示:Combo.text=Contract.Name.ToString()
而不是使用SelectedItem
属性只是一个建议。您可以在方法开始时注销selectedIndexChanged eventhandler(如果有),然后在结束时重新注册它。