设置 comboBox 控件key,value值,获取控件Text和value值

 private void FrmAddStudent_Load(object sender, EventArgs e)
 {
     StudentClassServer studentClassServer = new StudentClassServer();
     List<StudentClass> students = studentClassServer.GetStudentClasses(); //获取下拉框的数据

     //向集合第一个位置插入一条数据
     students.Insert(0,new StudentClass()
     {
         ClassId = 0,
         ClassName="请选择班级"
     });
     this.comboBox1.DataSource = students; // 将数据赋值给下拉框
     this.comboBox1.DisplayMember = "ClassName"; //设置下拉框的 label值
     this.comboBox1.ValueMember = "ClassId"; //设置下拉框的value值
     this.comboBox1.SelectedIndex = 1; //设置默认选择
 }

StudentClassServer 类此次省略了,如果想查看的话可以点击 https://www.cnblogs.com/tlfe/p/18243303 查看

如何获取当前选中 comboBox 控件的键值

this.comboBox1.Text.ToString(); //获取 Text值
Convert.ToInt32(this.comboBox1.SelectedIndex); //获取当前选中的索引
this.comboBox1.SelectedValue.ToString(); //获取当前 value值

 

 

posted @ 2024-06-12 09:36  龙卷风吹毁停车场  阅读(211)  评论(0)    收藏  举报