How to populate c# windows forms combobox?

后端 未结 2 1005
醉梦人生
醉梦人生 2020-12-03 04:00

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 com

2条回答
  •  没有蜡笔的小新
    2020-12-03 04:24

    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

提交回复
热议问题