VC++控件之多目标关联

来源:互联网 发布:mac qq截屏 编辑:程序博客网 时间:2024/06/08 10:31

一、新建工程

 

二、编辑对话框资源

 

 

三、添加变量、结构、函数

      1、添加变量

 

 

 

      2、添加结构

 

 

     3、添加函数

 

 

三、添加代码(红色部分

        1、添加“初始化”代码

BOOL CCListBoxDlg::OnInitDialog()
{
CDialog::OnInitDialog();

ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
ASSERT(IDM_ABOUTBOX < 0xF000);

CMenu* pSysMenu = GetSystemMenu(FALSE);
if (pSysMenu != NULL)
{
   CString strAboutMenu;
   strAboutMenu.LoadString(IDS_ABOUTBOX);
   if (!strAboutMenu.IsEmpty())
   {
    pSysMenu->AppendMenu(MF_SEPARATOR);
    pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
   }
}

SetIcon(m_hIcon, TRUE);    // Set big icon
SetIcon(m_hIcon, FALSE);   // Set small icon

// TODO: Add extra initialization here
   struct student str[3]={"常胜","生产","010","黄河","人事","011","李凌","质检","022"};
   int index;
   DWORD index2[3]={1,2,3};
   index=m_ListBox.AddString(str[0].name);
   m_ListBox.SetItemData(index,index2[0]);
   index=m_ListBox.AddString(str[1].name);
   m_ListBox.SetItemData(index,index2[1]);
   index=m_ListBox.AddString(str[2].name);
   m_ListBox.SetItemData(index,index2[2]);
UpdateData(FALSE);
return TRUE; // return TRUE unless you set the focus to a control
}

         2、添加函数代码

void CCListBoxDlg::OnSelchangeList1()
{
// TODO: Add your control notification handler code here
struct student str[3]={"常胜","生产","010","黄河","人事","011","李凌","质检","022"};
int index,i;
    DWORD index2;
index=m_ListBox.GetCurSel();
m_ListBox.GetText(index,m_name);
index2=m_ListBox.GetItemData(index);
   switch (index2)
   {
   case 1:
         i=0;
   break;
   case 2:
   i=1;
   break;
   case 3:
   i=2;
   break;
   default:i=100;
   }

m_id=str[i].ID;
m_class=str[i].classnumber;

UpdateData(FALSE);
}

四、编译

五、运行

 

 

六、函数说明

       1、CListBox::SetItemDataPtr函数声明

           int SetItemDataPtr(int nIndex,void *pData)

          nIndex:列表框内被选中列表项的索引

          pData:与该列表项相关联的数据的指针

          功能:将列表项中的索引和数据相关联。返回LB_ERR,则关联失败。

 

 

 

    2. CListBox::SetItemData成员函数:
  格式:int SetItemData(int nIndex,DWORD dwItemData);
  功能:设置与列表框中指定列表项相关的32位值。
  返回:若出错,则返回LB_ERR
  参数:
    nIndex-列表项的索引  
    dwItemData-指定与列表项相关的32位值
    CListBox::SetItemDataPtr成员函数:
 
   rString-获取的字符串对象。
  3.CListBox::GetText成员函数:   格式:void GetText(int nIndex,CString& rString);   功能:若获取某列表项的字符串。   参数:     nIndex-列表项的索引。