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的值为指定的值。

 

posted on 2013-01-24 11:36  北漂剑客  阅读(235)  评论(0编辑  收藏  举报