我想在VC代码中动态创建一个DataGrid,不是使用在Form资源中Insert ActiveX Control的方法,请问如何实现?谢谢!

解决方案 »

  1.   

    // 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);
       }
    }
      

  2.   

    不是设置数据源,我想要的效果是m_grid是在代码中create来的,而且必须在界面上显示,我用了IDataGridPtr的CreateInstance,但是在界面上无法显示。
      

  3.   

    先要通过菜单 project/add to project/components and controls/ 把datagrid control添加到项目中,然后就可以方便的使用CDataGrid类动态创建了。