// set datasource of DBGrid dynamically

void CDgDlg::OnOK() 
{ //notes : call AfxOleInit in CXXApp::InitInstance()
// I also add a line in stdafx.h 
//#import "c:\Program Files\Common Files\System\ado\msado15.dll" no_namespace rename("EOF", "EndOfFile")
   try
   {
      _ConnectionPtr pConn("ADODB.Connection");
      _RecordsetPtr  pRst("ADODB.Recordset");
      pConn->Open("Provider=sqloledb;Data Source=Dell1;"
         "Initial Catalog=testdb;User Id=sa;Password=;",
         "", "", adConnectUnspecified);
      pRst->Open(
         "table1",
         _variant_t((IDispatch *) pConn, true),
         adOpenStatic,
         adLockReadOnly,
         adCmdTable);
  //CDataGrid m_grid; is a member of CDgDlg.
m_grid.SetRefDataSource(pRst.Detach());
   }
   catch (_com_error &e)
   {
  char mybuf[10240];
      wsprintf(mybuf,"Description = '%s'\n", (char*) e.Description());
  AfxMessageBox(mybuf);
   }
}

解决方案 »

  1.   

    to:masterz,thank you!!
    我观察以上代码,您似乎使用了ado,但我在appwizard中已经设置了odbc数据源,然后我打算在DBgrid控件中显示数据源中某一表的内容,是不是不用再#import ado了?请指教,先谢了
      

  2.   

    use ADO is easy than MFC ODBC CRecordset class, because DBGrid is an activex control, it accept ADO Recordset, not MFC CRecordset.
    if you insist on using CRecordset, you can refer to 
    http://codeguru.earthweb.com/mfc_database/unbound_dbgrid.shtml
    Using DBGrid in unbound mode
      

  3.   

    ADO就ADO吧。
    那么我还有另外一个问题:假设DBgrid已经和某一数据源绑定,那我感觉如果想让DBgrid中按要求显示不同的表时,它应该有一个成员函数,这个成员函数有一个参数,是sql语句字符串,以实现从不同的表中select,请问又没有这个函数?如果有,是什么,如果没有,那么上述的功能怎么实现?
    多谢!!(其实我是因为项目的库很小才想用ODBC,但既然masterz推荐ado,那就改!)
      

  4.   

    create another recordset to open that table, set dbgrid datasource to the second recordset.
          pRst2->Open(
             "anothertable",
             _variant_t((IDispatch *) pConn, true),
             adOpenStatic,
             adLockReadOnly,
             adCmdTable);
    m_grid.SetRefDataSource(pRst2.Detach());