我编写了如下的代码,但是运行时comboBox控件并没有出现我想要的列值,该如何编写代码绑定才有效?
private void Max_Load(object sender, EventArgs e)
{ this.label2.Visible = false;
string sql = "select distinct ProductName from Products";
string cons = @"Data Source=LUOXIONGWEI\LUO;Initial Catalog=OrderSystem;Integrated Security=True"; SqlConnection con = null;
DataTable t = null; try
{
con = new SqlConnection();
con.ConnectionString = cons;
con.Open(); SqlCommand com = con.CreateCommand();
com.CommandText = sql; SqlDataAdapter p = new SqlDataAdapter();
DataSet set = new DataSet(); p.SelectCommand = com; p.Fill(set, "rt"); t = set.Tables["rt"];
this.comboBox1.DataSource =t;//这里绑定的,怎么无效啊!
}
catch (SqlException reer)
{
MessageBox.Show(reer.Message);
} finally
{
con.Close();
}
}
private void Max_Load(object sender, EventArgs e)
{ this.label2.Visible = false;
string sql = "select distinct ProductName from Products";
string cons = @"Data Source=LUOXIONGWEI\LUO;Initial Catalog=OrderSystem;Integrated Security=True"; SqlConnection con = null;
DataTable t = null; try
{
con = new SqlConnection();
con.ConnectionString = cons;
con.Open(); SqlCommand com = con.CreateCommand();
com.CommandText = sql; SqlDataAdapter p = new SqlDataAdapter();
DataSet set = new DataSet(); p.SelectCommand = com; p.Fill(set, "rt"); t = set.Tables["rt"];
this.comboBox1.DataSource =t;//这里绑定的,怎么无效啊!
}
catch (SqlException reer)
{
MessageBox.Show(reer.Message);
} finally
{
con.Close();
}
}
this.comboBox1.ValueMember = "作为值读取的字段或属性名";
this.comboBox1.DataSource=数据源; DataTable dt = new DataTable();
cmbox.DataSource = dt ;
cmbox.DisplayMember ="name";
cmbox.ValueMember="id";
后面加个:
this.comboBox1.DisplayMember ="ProductName";试试。
/// <summary>
/// 初始***
/// </summary>
/// <param name="combobox1"></param>
public static void chushihuabumen(ComboBox combobox1)
{
SqlConnection connection =link();
try {
connection.Open();
string sql = "SELECT * FROM bumen";
SqlCommand command = new SqlCommand(sql, connection);
SqlDataReader data;
data = command.ExecuteReader();
while (data.Read()) {
combobox1.Items.Add(Convert.ToString(data["bumen"]));
}
data.Close();
}
catch (Exception ex) {
MessageBox.Show(ex.Message);
}
finally {
connection.Close();
}
}