zoukankan      html  css  js  c++  java
  • C#:Combox实现key,value

    add方法传入的是一个object对象,利用这点可以传入一个自定义对象,选中时获得的也是一个完整对象。

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace WindowsFormsPassword
    {
        class User
        {
            private String id;
            private String name;
    
            public User(String id,String name)
            {
                this.id = id;
                this.name = name;
            }
    
            public String ID
            {
                get
                {
                    return id;
                }
                set
                {
                    this.id = value;
                }
            }
            public String Name
            {
                get
                {
                    return name;
                }
                set
                {
                    this.name = value;
                }
            }
    
    
            //必须重写ToString方法,不然显示的是类的信息
            public override string ToString()
            {
                return this.name;
            }
        }
    }
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Windows.Forms;
    
    namespace WindowsFormsPassword
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
            }
    
            private void Form1_Load(object sender, EventArgs e)
            {
                comboBox1.DropDownStyle = ComboBoxStyle.DropDownList;
                comboBox1.Items.Add(new User("1","张三"));
                comboBox1.Items.Add(new User("2", "李四"));
                comboBox1.Items.Add(new User("3", "王四"));
            }
    
            private void button1_Click(object sender, EventArgs e)
            {
             
               User user= comboBox1.SelectedItem as User;
                if (user != null)
                {
                    MessageBox.Show(String.Format("id={0},name={1}", user.ID, user.Name));
                }
            }
        }
    }

    转: https://www.cnblogs.com/huiy/p/14313336.html

  • 相关阅读:
    编译原理三大经典书籍
    c#之委托总结
    shell编程基础
    专家是什么?我真的想知道(转)
    linux sed
    判断一个脚本中的变量是否为空(转)
    JAVA Stack栈和Heap堆的区别(转)
    CMD获取当前目录的绝对路径 (转)
    RTP协议分析
    VS2010旗舰版安装图解
  • 原文地址:https://www.cnblogs.com/fps2tao/p/14717951.html
Copyright © 2011-2022 走看看