C 操作ComboBox控件

分享一下我老师大神的人工智能教程!零基础,通俗易懂!http://blog.csdn.net/jiangjunshow

也欢迎大家转载本篇文章。分享知识,造福人民,实现我们中华民族伟大复兴!

               

ComboBox控件是一个很容易使用出错的控件,在此将常用的

操作写下来,以备后用,也希望可以帮助到有需要的人。

----------------------------------------------------------------------------------------

1.让用户只能选择项。

很简单,设置ComboBox的属性DropDownStyle为DropDownList即可。


------------------------------------------------------------------------------------------

2.往ComboBox中添加新项。

 private void Form1_Load(object sender, EventArgs e)
        {
            this.cmbTest.Items.Add("A");
            this.cmbTest.Items.Add("B");
            this.cmbTest.Items.Add("C");
            this.cmbTest.Items.Add("D");
        }

//效果截图如下


------------------------------------------------------------------------------------

3.设置默认选择的项。

this.cmbTest.SelectedIndex = 3; //选择第四项,注意,编号从0开始


--------------------------------------------------------------------------------------------

4.获取选择的项的文本。

MessageBox.Show(this.cmbTest.SelectedItem.ToString());


----------------------------------------------------------------------------------------------

5.遍历ComboBox控件中每一项的文本:

            //从最后一项开始遍历            for (int i = this.cmbRoomId.Items.Count - 1; i >= 0;i-- )            {                this.cmbRoomId.SelectedIndex=i;//选择第i项                if (this.cmbRoomId.Text.Trim().Equals("Admin"))//判断项的文本                {                    break;//找到就停止遍历                }            }
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------

6.数据绑定:

在SQL2005数据库中,我有两列renterID和renterName

//截图如下


现在我想让ComboBox控件显示的是renterName,而ComboBox实际的值却是renterID,

我们如何做呢?

先看下我们写的SQL语句:select renterId,renterName from Renter

有了SQL语句,怎么获取数据集DataSet,这个不用我说了吧?

有了数据集后,我们就可以将其绑定到ComboBox中了。

代码如下:

 string sql="select renterId,renterName from Renter";//SqlHelper.GetConnection()的作用是获取一个数据库连接对象,这是我自己封装的方法,请灵活应变。 using (SqlDataAdapter da = new SqlDataAdapter(sql,SqlHelper.GetConnection()))               {                    DataSet ds = new DataSet();                    da.Fill(ds);//填充数据集,即获取数据集                    this.cmbRenter.DataSource = ds.Tables[0].DefaultView; //设置ComboBox的数据源                    this.cmbRenter.DisplayMember = "renterName"; //让ComboBox显示renterName列                    this.cmbRenter.ValueMember = "renterId"//让ComboBox实际的值为renterId列                }

数据绑定好后,我们如何获取renterId的值呢?代码如下:

MessageBox.Show(this.cmbRenter.SelectedValue.ToString()); 

//效果截图如下:

                 

-----------------------------------------------------------------------------------------------------------------------------------------------------------------------


您的十分满意是我追求的宗旨。

您的一点建议是我后续的动力。









           

给我老师的人工智能教程打call!http://blog.csdn.net/jiangjunshow

这里写图片描述

猜你喜欢

转载自blog.csdn.net/hfdgjhv/article/details/84099920