填充c#中的组合框 [英] populate combo box in c#
本文介绍了填充c#中的组合框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我不知道如何通过sql
的select语句的resault set来填充c#中的组合框,例如性别男性和女性。 plz帮我tanx
I dont know how to populate combobox in c# by resault set of select statement of sql
for example for gender male and female. plz help me tanx
推荐答案
试试这个:
Try this:
string strConn = "Data Source=SEZSW08;Initial Catalog=Nidhi;Integrated Security=True";
SqlConnection Con = new SqlConnection(strConn);
Con.Open();
string strCmd = "select companyName from companyinfo where CompanyName='" + cmbCompName.SelectedValue + "';";
SqlCommand Cmd = new SqlCommand(strCmd, Con);
SqlDataAdapter da = new SqlDataAdapter(strCmd, Con);
DataSet ds = new DataSet();
Con.Close();
da.Fill(ds);
cmbCompName.DataSource = ds;
cmbCompName.DisplayMember = "CompanyName";
cmbCompName.ValueMember = "CompanyName";
//cmbCompName.DataBind();
cmbCompName.Enabled = true;
如果是下拉列表,请使用
If it is a drop down then use
ddlCompName.Datasource=ds;
ddlCompName.Datavaluefield="CompanyName";
ddlCompName.DataTextfield="CompanyName";
ddlCompName.DataBind();
已添加的代码块[/ Edit]
Code blocks added[/Edit]
尝试这样的事情
--------------------------
Try Something like this
--------------------------
<pre> private void Form1_Load(object sender, EventArgs e)
{
//Making Sql Connection
SqlConnection cn = new SqlConnection();
//Setting Connection String Property
cn.ConnectionString = "data source = (local); initial catalog = TestDB; integrated security =sspi";
//Opening Connection
cn.Open();
//Creating Sql Command
SqlCommand cmd = new SqlCommand();
//Creating String Variable for SQL Command CommandProperty
string sqlQuery = "select GenderID,GenderType from Gender";
//Passing Query and Connection to the SQL Command
cmd = new SqlCommand(sqlQuery, cn);
//Creating Sql Data Adapter
SqlDataAdapter dAdapter = new SqlDataAdapter();
//Creating Data Table
DataTable dt = new DataTable();
//Initializing SQL Data Adapter Command Property
dAdapter.SelectCommand = cmd;
//Filling Data Table
dAdapter.Fill(dt);
//Populating Combo Box from Data Table
cmbGender.DataSource = dt;
//Setting Combo Box ValueMember Property
cmbGender.ValueMember = "GenderID";
//Setting Combo Box DisplayMember Property
cmbGender.DisplayMember = "GenderType";
}</pre>
实际上,您不应直接从表示层编写任何sql语句/执行数据库命令。您应该在dataaccess层中编写所有内容并从该层返回自定义实体。从表示层,您可以通过业务层获取该数据,并将其与您的下拉列表绑定。
In practice you should not write any sql statement/execute database command from directly your presentation layer. You should write all that in dataaccess layer and return custom entity from that layer. From presentation layer you get that data by Business Layer and bind it with your drop down list.
这篇关于填充c#中的组合框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文