0

我在接下来要从我目前拥有的数据集中填充组合框的事情上遇到了难题。我的数据库被称为“PID2db.mdb”,表被称为“客户”

        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();
        }
    }

任何帮助表示赞赏,谢谢

编辑:添加了新的代码段

4

2 回答 2

3

假设您有一个表格:

  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);
            }
        }
    }

如果有效,请告诉我在哪里,现在留下评论,否则有任何错误,你会在文本框中看到。

于 2013-01-09T15:53:31.910 回答
1

您需要创建一个新的 DataSet,用 Data 填充它,最后设置 ComboBox 的DataSourceDisplayMemberValueMember属性。这是代码:

using System.Data.OleDb;

            string strCon = Properties.Settings.Default.PID2dbConnectionString;
            OleDbConnection conn = new OleDbConnection(strCon);
            try {
                conn.Open();
                string strSql = "Select forename,surname from customer where customer id ='" + txtName.Text + "'";
                OleDbDataAdapter adapter = new OleDbDataAdapter(new OleDbCommand(strSql, conn);
                DataSet ds = new DataSet();
                adapter.Fill(ds);
                comboBox1.DataSource = ds.Tables[0];
                comboBox1.DisplayMember = "forename";
                comboBox1.ValueMember = "surname";
            }
            finally {
                conn.Close();
            }
于 2013-01-09T14:42:42.363 回答