利用数据库邦定控件是对winform编程常用的方法,以下是我的经验和方法:
using System;
using System.Windows.Forms;
using System.Data;
using System.Data.OleDb;
using Sybase.DataWindow;
using System.Data.SqlClient;
namespace Data
{
///
/// Form1 的摘要说明。
///
public class Form1 : System.Windows.Forms.Form
{
................//其它无关控件
private System.Data.OleDb.OleDbConnection con;
private System.Data.OleDb.OleDbCommand command;
private System.Data.OleDb.OleDbDataReader reader;
private System.Windows.Forms.ComboBox comboBox1;
..................//这里是窗体设计代码
private void Form1_Load(object sender, System.EventArgs e)
{
try
{
con = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=d:/pems/data.mdb");//创建数据库联接,这用利用的access数据库
con.Open();
command=con.CreateCommand();
command.CommandText="select t_name from teacher";//创建查询语句
reader=command.ExecuteReader();
while(reader.Read())
{
this.comboBox1.Items.AddRange(new object[] {reader["t_name"]});//邦定数据
}
reader.Close();
con.Close();
}
catch(Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
}
同样,如果要绑定其它的控件,如checklistBox等,都可以用同样的方法while循环是从数据库里面取出数据,然后用控件的.Items.AddRange方法添加进去就可以了