C#中comboBox和数据库的连接

虽然通过向导可以很容易的得到,但是考虑到后续功能,这种简单的实现方式只会给自己带来更多的麻烦,我决定自己写,不过写起来的确麻烦些,而且有很多意外考虑不到,但是先简单的实现吧。
添加了一个void用来实现控件和数据库的连接。
    private void data()
        {
             OleDbConnection kindConnection;
             OleDbCommand selectCommand;
             OleDbDataAdapter kindAdapter;
             DataSet kindDataSet;
            kindConnection = new OleDbConnection();
            kindConnection.ConnectionString =  @"Provider=Microsoft.Jet.OLEDB.4.0;" +
                @"Data source= E:/emp.mdb" ;
                selectCommand = new OleDbCommand("select id , name from kind",kindConnection);
                kindAdapter = new OleDbDataAdapter();
                kindAdapter.SelectCommand = selectCommand;
                kindDataSet = new DataSet();
           
            try
            {
                kindConnection.Open();
                // Insert code to process data.
               
                kindAdapter.Fill(kindDataSet,"kind");
                this.dataGrid1.DataSource = kindDataSet;
                this.dataGrid1.DataMember = "kind";
                this.comboBox1.DataSource = kindDataSet;
                this.comboBox1.DisplayMember = "kind.name";
   
            }
            catch (Exception ex)
            {
                MessageBox.Show("Failed to connect to data source"+ ex.ToString());
            }
            finally
            {
                kindConnection.Close();
            }
这一段
  kindConnection = new OleDbConnection();
            kindConnection.ConnectionString =  @"Provider=Microsoft.Jet.OLEDB.4.0;" +
                @"Data source= E:/emp.mdb" ;
                selectCommand = new OleDbCommand("select id , name from kind",kindConnection);
                kindAdapter = new OleDbDataAdapter();
                kindAdapter.SelectCommand = selectCommand;
                kindDataSet = new DataSet();
不能放在try中,不解,日后继续破解。
在form的构造函数中添加这个void即可。
万事开头难,终于实现这个功能,虽然只是小小的一步,但是毕竟迈了出来,可喜可贺。

你可能感兴趣的:(C#中comboBox和数据库的连接)