首页 > 代码库 > 组合框的绑定

组合框的绑定

 public partial class 组合框绑定数据 : Form
    {
        public 组合框绑定数据()
        {
            InitializeComponent();
        }

        private void btnBind_Click(object sender, EventArgs e)
        {
            string sql = "select * from ClassInfo";
            SqlConnection conn = DBHelper.GetConnection();
            SqlDataAdapter sda = new SqlDataAdapter(sql,conn);
            DataSet ds = new DataSet();
            sda.Fill(ds);
            DBHelper.CloseConnection(conn);
            DataTable table = ds.Tables[0];
            //给cboClass组合框绑定数据源
            this.cboClass.DataSource = table;
            //绑定文本(即显示给用户看的列)
            this.cboClass.DisplayMember = "ClassName";
            //绑定值(一般是主键列)
            this.cboClass.ValueMember = "ClassID";
        }

        private void cboClass_SelectedIndexChanged(object sender, EventArgs e)
        {
            //SelectedValue获取所选项的value值,Text获取所选项的文本
            MessageBox.Show(this.cboClass.SelectedValue+"-"+this.cboClass.Text);
        }
    }