如何填充 c# windows 窗体组合框? [英] How to populate c# windows forms combobox?

查看:24
本文介绍了如何填充 c# windows 窗体组合框?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何从 sql 数据库(带有 id 和 name 列的学生表)填充组合框,显示文本表示学生的姓名,组合框项目的值是该学生的 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

推荐答案

以下是适合您的重要属性.

Below are the important properties for you.

ComboBox.DataSource 属性

数据源可以是数据库、Web 服务或可以稍后用于生成数据绑定控件.当数据源属性已设置,项目集合无法修改.

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 属性

一个字符串,指定包含的对象属性的名称在 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 ("").

ComboBox.ValueMember 属性

表示包含的对象属性名称的字符串在 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));

有多种方法可以做到这一点.

There are various ways of doing this.

如何:从 Windows 窗体组合框中添加和删除项目

ComboBox.Items 属性

这篇关于如何填充 c# windows 窗体组合框?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆