ComboBox绑定数据的总结

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Collections;

namespace WindowsFormsApplication1
{
    public partial class Form4 : Form
    {
        public Form4()
        {            
            InitializeComponent();
            comboBox1.DropDownStyle = ComboBoxStyle.DropDownList;
        }

        private void Form4_Load(object sender, EventArgs e)
        {
            comboboxBind();
        }

        private void comboboxBind()
        {            
            IList<Category> categoryList = new List<Category>();
            categoryList.Add(new Category() { categoryId = 0, categoryName = "-请选择分类-" });
            Category model = null;
            for (int i = 0; i < 10; i++)
            {
                model = new Category()
                {
                    categoryId = i + 1,
                    categoryName = "分类" + (i + 1)
                };
                categoryList.Add(model);
            }            
            comboBox1.DataSource = categoryList;
            comboBox1.DisplayMember = "categoryName";
            comboBox1.ValueMember = "categoryId";
            comboBox1.SelectedValue = 0;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (comboBox1.SelectedValue.ToString().Equals("0"))
            {
                MessageBox.Show("请选择分类","异常信息");
                comboBox1.Focus();
                return;
            }
            int categoryId = Convert.ToInt32(comboBox1.SelectedValue);
            string categoryName = comboBox1.Text;
            MessageBox.Show("编号:" + categoryId.ToString() + ",名称:" + categoryName);
        }
    }


    public class Category
    {
        public int categoryId { get; set; }
        public string categoryName { get; set; }
    }


}

需要注意的是:

让下拉框不可编辑:设置属性DropDownStyle的值为DropDownList。

修改的时候选择指定值的方法:设置属性SelectedValue的值为指定的值。

 

转载于:https://www.cnblogs.com/jiangrod/archive/2013/01/24/2874598.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值