如何填充c#窗体组合框? [英] How to populate c# windows forms combobox?
问题描述
如何从sql数据库填充组合框(学生表的id和名称列),显示文本表示学生的名字,combobox项目的值是该学生的ID,当我得到组合框的值我将获得id值
How can I fill a combobox from sql database ( students table with id, and name columns ) , the display text represents the name of a student and the value of the item of combobox is the id for that student that when I get the value of the combobox I will get the id value
推荐答案
以下是您的重要属性。
数据源可以是数据库,Web服务或可以使用
的对象来生成数据绑定控制。当设置DataSource
属性时,无法修改items集合。
A data source can be a database, a Web service, or an object that can later be used to generate data-bound controls. When the DataSource property is set, the items collection cannot be modified.
一个字符串,指定由DataSource属性指定的集合中包含
的对象属性的名称。默认值为
一个空字符串()。
A String specifying the name of an object property that is contained in the collection specified by the DataSource property. The default is an empty string ("").
一个字符串,表示由DataSource属性指定的集合中包含
的对象属性的名称。默认为
一个空字符串()。
A String representing the name of an object property that is contained in the collection specified by the DataSource property. The default is an empty string ("").
DataTable dataTable = GetDataTable("Select * from Student"); // You have to implement the ways to retrieve data from the database.
comboBox1.Datasource = dataTable;
comboBox1.DisplayMember = StudentName; // Column Name
comboBox1.ValueMember = StuentId; // Column Name
如果要以编程方式添加项目,这里有一种方法。
Here is one way if you want to add items programmatically.
private class Item
{
public string _Name;
public int _Id
public Item(string name, int id)
{
_Name = name;
_Id = id;
}
public string Name
{
get { return _Name; }
set { _Name = value; }
}
public string Id
{
get { return _Id; }
set { _Id = value; }
}
}
comboBox1.DisplayMember = "Name";
comboBox1.ValueMember = "Id";
comboBox1.Items.Add(new Item("Student 1", 1));
comboBox1.Items.Add(new Item("Student 2", 2));
comboBox1.Items.Add(new Item("Student 3", 3));
有多种方法。
这篇关于如何填充c#窗体组合框?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!