MFC 列表框 CListBox

发布时间 2023-12-03 18:42:28作者: double64


▲ 增删改查

6)列表框CListBox	
	a) 给列表框添加一个字符串 CListBox::AddString
	b) 选中列表列表框某一项,自动触发事件:LBN_SELCHANGE
		1)获取当前选中项 CListBox::GetCurSel
		2)获取指定位置的内容 CListBox::GetText
	c) 删除指定位置的字符串 CListBox::DeleteString
	d) 在指定位置插入字符串 CListBox::InsertString

/***新增***/

void CMFCApplication1LiBiaoDlg::OnBnClickedButton1()
{
    UpdateData(TRUE);
    if (m_Str.GetLength() == 0) {
        MessageBox(TEXT("内容不能为空"), TEXT("提示"));
        return;
    }

    m_listBox.AddString(m_Str);
    m_Str.Empty();  // 清一下列表框
    UpdateData(FALSE);
}

/***删除***/
void CMFCApplication1LiBiaoDlg::OnBnClickedButton2()
{
    int sel_idx = m_listBox.GetCurSel();
    m_listBox.DeleteString(sel_idx);
    UpdateData(FALSE);
}


/***选中项变化***/
void CMFCApplication1LiBiaoDlg::OnLbnSelchangeList1()
{
    int selIndex = m_listBox.GetCurSel();
    m_listBox.GetText(selIndex, m_Str);
    UpdateData(FALSE);
}

/***修改***/
void CMFCApplication1LiBiaoDlg::OnBnClickedButton3()
{
    UpdateData(TRUE);
    if (m_Str.GetLength() == 0) {
        MessageBox(TEXT("内容不能为空"), TEXT("提示"));
        return;
    }

    int selIndex = m_listBox.GetCurSel();
    if (selIndex < 0) {
        MessageBox(TEXT("请选中要修改的项"), TEXT("提示"));
        return;
    }

    m_listBox.DeleteString(selIndex);
    m_listBox.InsertString(selIndex, m_Str);

    UpdateData(FALSE);
}