【发布时间】:2019-07-02 15:10:31
【问题描述】:
我填充组合框从数据库中获取数据
这是我的数据库结构:
Table names
ID ------ Name
1 ------ John
2 ------ Sarah
3 ------ Peter
这是我的班级结构
// Class structure
public class Names
{
public int id;
public string name;
}
这就是我声明我的字典以及我如何设置它的方式
// Declare dictionary
Dictionary<int, string> dataSouceNames;
public MyProgram()
{
InitializeComponent();
dataSouceNames = getComboDataSourceNames();
}
//Dictionary
private Dictionary<int, string> getComboDataSourceNames()
{
Dictionary<int,string> comboSource = new Dictionary<int,string>();
List<Names> res = dataProvider.getAllNames();
foreach (Names item in res)
{
comboSource.Add(item.id, item.nome);
}
return comboSource;
}
这是我用来从数据库中获取数据的 SQL
getAllNames()
{
string sql = "SELECT * FROM names";
}
最后我如何填充我的 ComboBox
// Function fill combobox
private void initComboNames()
{
cmbNames.DataSource = new BindingSource(dataSourceNames, null);
cmbNames.DisplayMember = "Text";
cmbNames.ValueMember = "Value";
}
然后我尝试按键选择组合框中的项目:
cmbNames.SelectedItem = Names.ID // WHERE Names.ID is number "2"
我希望输出“Sarah”为 SelectedIndex,但我知道我做错了。
【问题讨论】:
-
什么是数据源?
dataSourceNames还是dataSouceCantieri?如果是dataSouceCantieri,那么cmbNames.SelectedItem = new KeyValuePair<int, string>(Names.ID, dataSouceCantieri[Names.ID]);。你应该有.DisplayMember = "Value"(对应于字符串,Name)和.ValueMember = "Key"。dataSourceNames未声明且未确定。 -
你好@Jimi 你的解决方案已经奏效了,同时我不明白你做了什么!我读到这不是聊天,但如果你能解释一下你写了什么,那就太酷了。顺便说一句,谢谢