C# 使用数据源加载组合框

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9355877/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 07:00:57  来源:igfitidea点击:

loading combobox with datasource

c#

提问by Sreenath Ganga

i want to fill a combobox with data from the database when the page load I had written the code as below

我想在页面加载时用数据库中的数据填充组合框我编写的代码如下

private void QuotationForm_Load(object sender, EventArgs e)
        {
            MessageBox.Show("hghjgvhg");
            comboboxload();
        }




 public void comboboxload()
        {

            OleDbConnection oleDbConnection1 = new System.Data.OleDb.OleDbConnection(connString);
            oleDbConnection1.Open();
            OleDbCommand oleDbCommand1 = new System.Data.OleDb.OleDbCommand("Select jobpk,jobecode from  jobcodemastertable",oleDbConnection1);
            OleDbDataReader reader = oleDbCommand1.ExecuteReader();
            DataTable dt = new DataTable();
            dt.Columns.Add("jobpk", typeof(int));
            dt.Columns.Add("jobcode", typeof(string));
            dt.Load(reader);
            cmbjobcode.ValueMember = "jobpk";
            cmbjobcode.DisplayMember = "jobcode";
            cmbjobcode.DataSource = dt;
            oleDbConnection1.Close();  
        }

it doesnot deturns an error or exception but doesnot load the combobox with data values

它不会引发错误或异常,但不会使用数据值加载组合框

采纳答案by Ajeesh M

You may need to bind datatable's view with combo box

您可能需要使用组合框绑定数据表的视图

cmbjobcode.DataSource = dt.DefaultView;

回答by user1216891

You're missing the DataBind method

您缺少 DataBind 方法

dt.Load(reader);
cmbjobcode.ValueMember = "jobpk";
cmbjobcode.DisplayMember = "jobcode";
cmbjobcode.DataSource = dt;
//here
cmbjobcode.DataBind();
oleDbConnection1.Close();

回答by Ebad Masood

You have to call DataBind method on your combo. Thats why its not populating.

您必须在组合上调用 DataBind 方法。这就是为什么它没有填充。

回答by Manly

try this

尝试这个

comboBox1.DataSource = ds.Tables[0];
comboBox1.ValueMember = "id";
comboBox1.DisplayMember = "name";