如何从Access数据集/数据库填充组合框 [英] How to populate a combobox from a Access dataset / Database

查看:118
本文介绍了如何从Access数据集/数据库填充组合框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

ive在下一步该怎么做上打了砖墙,以从我当前拥有的数据集中填充一个组合框。我的数据库称为 PID2db.mdb,表名为客户

ive hit a brick wall on what to do next to populate a combobox from a data set currently i have. my database is call "PID2db.mdb" and the table is called "Customer"

        string strCon = Properties.Settings.Default.PID2dbConnectionString;
        OleDbConnection conn = new OleDbConnection(strCon);
        try {
            conn.Open();
            string strSql = "Select forename,surname from customer where [customerID] ='" + txtName.Text + "'";
             OleDbDataAdapter adapter = new OleDbDataAdapter(new OleDbCommand(strSql, conn));
            DataSet ds = new DataSet();
            adapter.Fill(ds);
            cboName.DataSource = ds.Tables[0];
            cboName.DisplayMember = "forename";
            cboName.ValueMember = "surname";
        }
        finally {
            conn.Close();
        }
    }

感谢任何帮助,谢谢

编辑:添加了新的代码段

edit: added new code segments

推荐答案

假设您的表单具有以下内容:

Assuming you have a Form with:


  1. 名为cboName的组合框

  2. 名为txtName的文本框

尝试一下:

    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();

            LoadCustomerOnCombo();
        }

        private void LoadCustomerOnCombo()
        {
            string strCon = Settings.Default.PID2dbConnectionString;

            try
            {
                using (OleDbConnection conn = new OleDbConnection(strCon))
                {
                    conn.Open();
                    string strSql = "SELECT forename &\" \" & surname AS FullName, surname FROM customer"; //WHERE [customerID] ='" + txtName.Text + "'";
                    OleDbDataAdapter adapter = new OleDbDataAdapter(new OleDbCommand(strSql, conn));
                    DataSet ds = new DataSet();
                    adapter.Fill(ds);
                    cboName.DataSource = ds.Tables[0];
                    cboName.DisplayMember = "FullName";
                    cboName.ValueMember = "surname";
                }     
            }
            catch (Exception ex)
            {
                txtName.Text = ex.Message;
                Console.WriteLine(ex.Message);
            }
        }
    }

如果可行,请告诉我如何
,在此处留下评论的位置,否则有任何错误,您会在文本框内看到。

If worked so please tell me how is the where, left commented at the moment, else there are any errors, you'll see inside the textbox.

这篇关于如何从Access数据集/数据库填充组合框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆