1

拜托,我有列表控件,我想在列表控件上显示我的查询结果。程序运行没有错误,但它没有在列表控件上显示 SQL 结果。

BOOL CClassDialog::OnInitDialog()
{
    CDialogEx::OnInitDialog();

    // TODO:  Add extra initialization here
    CString DSN;
    DSN = _T("DRIVER=SQL Server;SERVER=DESKTOP-
DICUCDS\\SQL2K14;Trusted_Connection=Yes;APP=Microsoft\x00ae Visual Studio\x00ae 2013;WSID=DESKTOP-
DICUCDS;DATABASE=School");

    CDatabase aDB; 
    try {
        aDB.OpenEx(DSN);  

        CRecordset aRS(&aDB); 
        aRS.Open(CRecordset::forwardOnly, (L"SELECT DISTINCT Myclass FROM MyFacts"));  

        // populate Grids
        ListView_SetExtendedListViewStyle(m_classlist, LVS_EX_GRIDLINES);

        // Column width and heading
        m_classlist.InsertColumn(1, L"Class", LVCFMT_LEFT, -1, 1);

        m_classlist.InsertColumn(2, L"Age", LVCFMT_LEFT, -1, 1);
        m_classlist.SetColumnWidth(0, 120);
        m_classlist.SetColumnWidth(1, 200);
        m_classlist.SetColumnWidth(2, 200);

        while(!aRS.IsEOF())   
        {
            CString strValue;
            aRS.GetFieldValue(L"Myclass",  strValue);
            m_classlist.SetItemText(-1, 1, strValue);
            //strValue.AddString(strValue);

            aRS.MoveNext();
        }
        aRS.Close();
        aDB.Close();
    }
    catch (CDBException * ex)
    {
        TCHAR buf[255];

        ex->GetErrorMessage(buf, 255);

        CString strPrompt(buf);
        AfxMessageBox(strPrompt);
    }

    return TRUE;  // return TRUE unless you set the focus to a control
                  // EXCEPTION: OCX Property Pages should return FALSE
}

void CClassDialog::ResetListControl()
{
    m_classlist.DeleteAllItems();
    int iNbrOfColumns;

    CHeaderCtrl* pHeader = (CHeaderCtrl*)m_classlist.GetDlgItem(0);

    if (pHeader) {
        iNbrOfColumns = pHeader->GetItemCount();
    }

    for (int i = iNbrOfColumns; i >= 0; i--) {
        m_classlist.DeleteColumn(i);
    }
}
4

1 回答 1

1

你确定这是对的吗?m_classlist.SetItemText(-1, 1, strValue);

如果您研究CListCtrl(例如,此处)的官方文档,您将看到:

CString strText;

int nColumnCount = m_myListCtrl.GetHeaderCtrl()->GetItemCount();

// Insert 10 items in the list view control.
for (int i = 0; i < 10; i++)
{
    strText.Format(TEXT("item %d"), i);

    // Insert the item, select every other item.
    m_myListCtrl.InsertItem(LVIF_TEXT | LVIF_STATE, i, strText,
        (i % 2) == 0 ? LVIS_SELECTED : 0, LVIS_SELECTED, 0, 0);

    // Initialize the text of the subitems.
    for (int j = 1; j < nColumnCount; j++)
    {
        strText.Format(TEXT("sub-item %d %d"), i, j);
        m_myListCtrl.SetItemText(i, j, strText);
    }
}

您正在引用SetItemText但实际上并未将任何元素添加到列表中。之前的代码显示了一个示例:

// Insert the item, select every other item.
m_myListCtrl.InsertItem(LVIF_TEXT | LVIF_STATE, i, strText,
    (i % 2) == 0 ? LVIS_SELECTED : 0, LVIS_SELECTED, 0, 0);

我并不是说您必须使用那组特定的参数。但关键是您必须先将一个项目插入到列表中,然后才能更新它的属性。甚至在将其添加到列表时设置属性。

于 2021-03-26T20:51:14.047 回答