简体   繁体   中英

How to populate c# windows forms combobox?

如何从sql数据库填充一个组合框(带有id和名称列的学生表),显示文本代表学生的名字,组合框项目的值是该学生的id,当我得到的值时组合框我会得到id值

Below are the important properties for you.

ComboBox.DataSource Property

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 ("").

ComboBox.ValueMember Property

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));

There are various ways of doing this.

How to: Add and Remove Items from a Windows Forms ComboBox

ComboBox.Items Property

First off you need to figure out how you're going to get the data back from the DB, but I'll assume you either know that or intend to ask another question in regards to that. From there, your best bet is to bind some collection to the ComboBox . Here is an example of doing that with a DataSet . You can also bind to List<T> or other IEnumerable<T> , which would make more sense if you're going to use LINQ to get at the data. Here is a question here on SO about binding a List to a ComboBox Perhaps you could tell us how you intend to get at the data so we could give you a more tailored answer?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM