首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

MFC 動態向列表控件插入數據的正確時機與方法

     編輯:程式設計綜合問答

錯誤現象

在菜單響應函數 `CTextView::OnShowCol()` 中構造 `ShowOut` 對話框對象,直接調用 `ShowOut.ShowList.InsertColumn()` 報錯。

根因分析

`ShowOut` 為棧上對象,此時對話框窗口尚未創建(`DoModal`/`Create` 未調用),`ShowList` 控件對應的 `HWND` 為 `NULL`,發送 `LVM_INSERTCOLUMN` 消息失敗。

正確模式

  1. 數據傳遞給對話框:通過構造函數或 `SetData()` 將列定義、數據傳入 `ShowOut`。
  2. 在 `OnInitDialog` 中初始化控件:此時控件已創建,可安全調用 `InsertColumn`、`InsertItem`、`SetItemText`。
  3. 模態顯示:調用 `dlg.DoModal()` 進入消息循環。

代碼示例

// ShowOut.h
class ShowOut : public CDialogEx {
public:
    ShowOut(const vector& cols, CWnd* pParent = nullptr);
    vector m_cols;
    CListCtrl ShowList;
    // ...
};

// ShowOut.cpp
ShowOut::ShowOut(const vector& cols, CWnd* pParent)
    : CDialogEx(IDD_SHOWOUT, pParent), m_cols(cols) {}

BOOL ShowOut::OnInitDialog() {
    CDialogEx::OnInitDialog();
    for (int i = 0; i < m_cols.size(); ++i) {
        ShowList.InsertColumn(i, m_cols[i].name, LVCFMT_LEFT, m_cols[i].width);
    }
    // 插入行數據...
    return TRUE;
}

// 調用處
void CTextView::OnShowCol() {
    vector cols = GetColumnsFromDocument();
    ShowOut dlg(cols);
    dlg.DoModal(); // 此處創建窗口、執行 OnInitDialog
}

MFC 列表控件動態插入數據,對話框未創建時操作控件導致失敗,正確在 OnInitDialog 初始化,構造函數傳遞數據。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved