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();
}
}
感谢任何帮助,谢谢
编辑:添加了新的代码段
答案 0 :(得分:3)
假设您有一张表格:
试试这个:
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);
}
}
}
如果是这样的话,请告诉我当前的评论是什么,留下评论,否则有任何错误,你会在文本框内看到。
答案 1 :(得分:1)
您需要创建一个新的DataSet,用Data填充它,最后设置ComboBox的DataSource,DisplayMember和ValueMember属性。这是代码:
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();
}