如何填充的C#Windows窗体ComboBox? [英] How to populate c# windows forms combobox?
问题描述
我怎么能填补SQL数据库(学生ID表,和名称列)组合框,显示文本重presents学生和组合框的项目值的名称是ID为学生当我得到的组合框的值,我会得到的值id
下面是对你的重要属性。
一个数据源可以是数据库,Web服务,或一个对象, 稍后被用来生成数据绑定控件。当数据源 属性设置,该项目集不能被修改。
<一个href="http://msdn.microsoft.com/en-us/library/system.windows.forms.listcontrol.displaymember.aspx">ComboBox.DisplayMember物业
这包含一个字符串,指定对象属性的名称 由DataSource属性指定的集合。缺省值是 一个空字符串()。
<一个href="http://msdn.microsoft.com/en-us/library/system.windows.forms.listcontrol.valuemember.aspx">ComboBox.ValueMember物业
一个字符串再presenting对象属性的名称中包含 由DataSource属性指定的集合。缺省值是 一个空字符串()。
DataTable中的dataTable = GetDataTable(从学生*); //你必须要实现从数据库中检索数据的方式。
comboBox1.Datasource = dataTable的;
comboBox1.DisplayMember = StudentName; //列名
comboBox1.ValueMember = StuentId; //列名
下面是一种方法,如果你想以编程方式添加物品。
私有类项目
{
公共字符串名称;
公众诠释标识
公共项目(字符串名称,诠释ID)
{
名称=名称;
ID = ID;
}
}
comboBox1.Items.Add(新项目(学生1,1));
comboBox1.Items.Add(新项目(学生2,2));
comboBox1.Items.Add(新项目(学生3,3));
下面是一些例子。有这样做的各种方法。
<一个href="http://msdn.microsoft.com/en-us/library/system.windows.forms.combobox.items.aspx">ComboBox.Items物业
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
Below are the important properties for you.
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.
ComboBox.DisplayMember Property
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 ("").
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;
}
}
comboBox1.Items.Add(new Item("Student 1", 1));
comboBox1.Items.Add(new Item("Student 2", 2));
comboBox1.Items.Add(new Item("Student 3", 3));
Below are some more examples. There are various ways of doing this.
How to: Add and Remove Items from a Windows Forms ComboBox
这篇关于如何填充的C#Windows窗体ComboBox?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!