专注于.NET编程学习和技术分享

WinForm中Combobox控件用Datatable同时绑定Key和Value

Combobox绑定通过数据源绑定Key和Value,可以通过Key设置和获取相应的Value值,绑定代码如下:

private void Form1_Load(object sender, EventArgs e)
        {
            DataTable dt = new DataTable();
            dt = CreateDataTable();
            cmbProvince.DisplayMember = dt.Columns[1].ColumnName;
            cmbProvince.ValueMember = dt.Columns[0].ColumnName;
            cmbProvince.DataSource = dt;
        }

        /// <summary>
        /// 模拟数据
        /// </summary>
        /// <returns></returns>
        private DataTable CreateDataTable()
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("Key");
            dt.Columns.Add("Value");
            dt.Rows.Add("P01", "北京");
            dt.Rows.Add("P02", "上海");
            dt.Rows.Add("P03", "广东");
            dt.Rows.Add("P04", "深圳");
            return dt;
        }

        private void cmbProvince_SelectedValueChanged(object sender, EventArgs e)
        {
            Console.WriteLine(cmbProvince.SelectedValue + ":" + cmbProvince.Text); //如选择的时上海,结果是 P02:上海
        }
未经允许不得转载:墨鱼巴巴 » WinForm中Combobox控件用Datatable同时绑定Key和Value
分享到: 更多 (0)

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址