我有一个函数,它填充下拉列表并设置BindingSource中的显示和值成员,但我不知道如何只选择所选项的值。
Dictionary bindingsource population:
public Dictionary<int, string> Get_List_of_ManualSchemes()
{
Dictionary<int, string> comboSource = new Dictionary<int, string>();
using (SqlConnection cnn = new SqlConnection(connectionString))
{
cnn.Open();
string query = "SELECT [idGMRScheme],[SchemeName] FROM [DBA_Admin].[dbo].[GMR_Schemes]";
using (SqlCommand command = new SqlCommand(query, cnn))
using (SqlDataReader reader = command.ExecuteReader())
while (reader.Read())
{
comboSource.Add((int)reader["idGMRScheme"], (string)reader["SchemeName"]);
}
}
return comboSource;
}
用它填充组合:
public void Populate_ManualSchemes_Combolist(Dictionary<int, string> comboSource)
{
cb_SchemesManual.DataSource = new BindingSource(comboSource, null);
cb_SchemesManual.ValueMember = "value";
cb_SchemesManual.DisplayMember = "text";
}
我尝试着:
cb_ManualSchemes.SelectedValue
并返回显示的文本,而不是id,当我尝试时:
cb_ManualSchemes.SelectedText
它什么都不返回
答案 0 :(得分:3)
因为您使用的字典是键值对的集合。显示成员和值成员必须与字典中项目的属性匹配
尝试以下
cb_SchemesManual.ValueMember = "Key";
cb_SchemesManual.DisplayMember = "Value";
答案 1 :(得分:1)
使用以下代码对您的组合框进行外壳,以便您可以使用cb_ManualSchemes.SelectedValue
public void Populate_ManualSchemes_Combolist(Dictionary<int, string> comboSource)
{
cb_SchemesManual.DataSource=comboSource;
cb_SchemesManual.ValueMember = "Key";
cb_SchemesManual.DisplayMember = "Value";
}
答案 2 :(得分:0)
尝试使用DataTable for comboSource而不是Dictionary。
public DataTable Get_List_of_ManualSchemes()
{
DataTable comboSource = new DataTable();
comboSource.Columns.Add("value", typeof(Int32));
comboSource.Columns.Add("text");
DataRow newRow;
using (SqlConnection cnn = new SqlConnection(connectionString))
{
cnn.Open();
string query = "SELECT [idGMRScheme],[SchemeName] FROM [DBA_Admin].[dbo].[GMR_Schemes]";
using (SqlCommand command = new SqlCommand(query, cnn))
using (SqlDataReader reader = command.ExecuteReader())
while (reader.Read())
{
newRow = comboSource.NewRow();
newRow["value"] = (Int32)reader["idGMRScheme"];
newRow["text"] = reader["SchemeName"].ToString();
comboSource.Rows.Add(newRow);
}
}
return comboSource;
}
public void Populate_ManualSchemes_Combolist(DataTable comboSource)
{
cb_SchemesManual.DataSource = comboSource;
cb_SchemesManual.ValueMember = "value";
cb_SchemesManual.DisplayMember = "text";
}