C#中comboBox用代码绑定数据库中在某一列。用处:跟radioButton联系在一起,可以根据radioButton在选择而在comboBox显示出不同的值。
private void radioButton1_Click(object sender, EventArgs e)
{
comboBox1.Items.Clear(); //清空ComBox
string connStr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=mydb.mde;Jet OLEDB:Database Password=asd123456789";
OleDbConnection con = new OleDbConnection(connStr); //创建一个新连接
con.Open();
OleDbCommand cmd = con.CreateCommand();
cmd.CommandText = "SELECT 年份 FROM 任务记录"; //在这儿写sql语句
OleDbDataReader sdr = cmd.ExecuteReader(); //创建一个OracleDateReader对象
while (sdr.Read())
{
comboBox1.Items.Add(sdr[0].ToString()); //循环读区数据
}
con.Close();
}
因为从数据库读入的数据会有很多重复的,在comboBox下拉框中要把重复在合并在一起,可以用下面在语句替代上面在sql查询语句:
cmd.CommandText = "SELECT distinct 年份 FROM 任务记录";
string sql ="select 物品名,物品属性 from prop";
richTextBox.text=""
SqlDataAdapter myda = new SqlDataAdapter(sqlstr, objConnection);
DataTable mydt = new DataTable();
myda.Fill(mydt);
mycon.Close();
foreach (DataRow dr in mydt.Rows)
{
comboBox.Items.Add(dr[0].ToString());
richTextBox.text+=dr[1].ToString());
}
全代码:
private void Form1_Load(object sender, EventArgs e)
{
string strConnection = "Provider=Microsoft.Jet.OleDb.4.0;";
strConnection += @"Data Source=D:\Data\DotaData.mdb";
OleDbConnection objConnection = new OleDbConnection(strConnection);
objConnection.Open();
string sql = "select 物品名,物品属性 from Prop";
OleDbCommand cmd = new OleDbCommand(sql,objConnection);
OleDbDataReader reader = cmd.ExecuteReader();
comboBox1.Items.Clear();
while(reader.Read()){
comboBox1.Items.Add((string)reader["物品名"]); //添加物品名到combobox
richTextBox1.Text + = (string)reader["物品属性"]); //添加物品属性刀richTextBox
}
cmd.Dispose();
reader.Close();
objConnection.Close();
}