我希望向下拉框列表中添加数据,但不确定正确的方法。数据来自原始SQL语句。
我已经尝试直接从数据库绑定数据,但对于我来说,所有这些绑定和数据集是如何工作并不清楚,因此我决定跳过这一步,在您的帮助下将数据插入到下拉框中。
我在网上看到的代码如下:
public partial class Form1 : Form {
// Content item for the combo box
private class Item {
public string Name;
public int Value;
public Item(string name, int value) {
Name = name; Value = value;
}
public override string ToString() {
// Generates the text shown in the combo box
return Name;
}
}
public Form1() {
InitializeComponent();
// Put some stuff in the combo box
comboBox1.Items.Add(new Item("Blue", 1));
comboBox1.Items.Add(new Item("Red", 2));
comboBox1.Items.Add(new Item("Nobugz", 666));
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e) {
// Display the Value property
Item itm = (Item)comboBox1.SelectedItem;
Console.WriteLine("{0}, {1}", itm.Name, itm.Value);
}
}
您是否真的需要创建一个新类,只是为了向组合框添加数据? 此外,使用上述技术,我的代码如下:
while (rdata.Read()){
String Name = (String)rdata["vetName"];
Name = Name.Trim();
String Surname = (String)rdata["vetSurname"];
Surname = Surname.Trim();
String id = rdata["vetID"].ToString().Trim();
MessageBox.Show("ID " + id);
int value1 = Convert.ToInt32(id);
MessageBox.Show("value1 " + value1);
String display = (String)Name + " " + Surname;
editVetComboBox.Items.Add(new Item(display, 2));
}
问题在于,虽然下拉框中填充了名字和姓氏,但值(ID)未被添加。 有什么想法吗?
非常感谢, Richard
Console.WriteLine
,可以提供这样的信息,但您没有将其提供给我们。如果代码中有注释,如“//此处我有正确的值6”和“//由于某种原因,这里的值是1243”,那么回答这样的问题会更容易。 - Snowbear