问题
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();
}
}
any help is appreciated, thanks
edit: added new code segments
回答1:
Assuming you have a Form with:
- Combobox named cboName
- TextBox named txtName
Try this :
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.
回答2:
You need to create a new DataSet, fill it with Data and finally set the ComboBox's DataSource, DisplayMember and ValueMember properties. Here is the code:
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();
}
来源:https://stackoverflow.com/questions/14237639/how-to-populate-a-combobox-from-a-access-dataset-database