C# ComboBox 使用示例

效果图

 

 form1.Designer.cs

 private System.Windows.Forms.ComboBox cmbInstallResult;
// 
// cmbInstallResult
// 
this.cmbInstallResult.Cursor = System.Windows.Forms.Cursors.Hand;
this.cmbInstallResult.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.cmbInstallResult.Font = new System.Drawing.Font("微软雅黑", 10.28571F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
this.cmbInstallResult.FormattingEnabled = true;
this.cmbInstallResult.Location = new System.Drawing.Point(677, 137);
this.cmbInstallResult.Name = "cmbInstallResult";
this.cmbInstallResult.Size = new System.Drawing.Size(200, 31);
this.cmbInstallResult.TabIndex = 182;

form1.cs

从数据库取值,赋到 ComboBox 下拉菜单中 两方法

方法一

string strSql_InstallWorker = "SELECT first_name FROM user where role_name='安装人员' " + " and title='" + Program.globalCurrentUserTitle + "'" + " and deleted=0  order by date_entered asc";
DataTable dtComboBox_InstallWorker = clsDBHelperMySQL.m_Query(strSql_InstallWorker);//执行sql 
this.cmbInstallWorker.Items.Add("--请选择--");
foreach (DataRow row in dtComboBox_InstallWorker.Rows)
{
     this.cmbInstallWorker.Items.Add(row[0]);
}
this.cmbInstallWorker.SelectedIndex = 0;

方法二

private void setComboBoxOption(ref ComboBox objComboBox, string strItemName, string strDefaultOption)
{
            string strSql = "SELECT value_name FROM item_value where deleted=0 and value_name<>'' and item_name='" + strItemName + "' order by orderby+0 asc ";
            DataTable dtComboBox = clsDBHelperMySQL.m_Query(strSql);//执行sql 
            DataRow newRow = dtComboBox.NewRow();
            newRow[0] = strDefaultOption;// 给新行赋值  "--请选择--"
            dtComboBox.Rows.InsertAt(newRow, 0);//插入至第一行
            objComboBox.DataSource = dtComboBox;
            objComboBox.ValueMember = "value_name";//绑定
            objComboBox.DisplayMember = "value_name";
}

调用方式

//安装情况---------------
this.setComboBoxOption(ref this.cmbInstallResult, "查询安装情况", "--请选择--");

组合成SQL查询条件时

string strInstallResult = this.cmbInstallResult.Text;
if (strInstallResult != "" && strInstallResult != "--请选择--")
{
    strWhere = strWhere + " and ( install_result ='" + strInstallResult + "' )";
}

 

posted @ 2024-06-14 16:18  海乐学习  阅读(10)  评论(0编辑  收藏  举报