Software & Finance





Visual C++ MFC Dialog App - Student Information System - Search by Name, Age, City, etc





I have come up with student information system using Visual C++ - Dialog based application. Scroll down to see the download instructions and output. You can add, edit, delete students along with search by name, age, city, country, GPA, etc.



Source Code


//StudentData.h

 

#pragma once

 

#pragma warning(disable:4996)

#pragma warning(disable:4267)

#pragma warning(disable:4018)

#pragma warning(disable:4101)

 

#include <vector>

#include <map>

#include <string>

 

 

struct CStudent

{

public:

    int m_idx;

    char m_name[64];

    char m_country[32];

    char m_city[64];

    int m_age;

    double m_mark_gpa;

 

    CStudent()

    {

        m_idx = 0;

        strcpy(m_name, "");

        strcpy(m_city, "");

        strcpy(m_country, "");

        m_age = 0;

        m_mark_gpa = 0.0;

    }

};

 

struct CStudents

{

    char m_fileName[1024];

    std::vector<CStudent> m_studList;

    std::map<int, std::vector<int> > m_ageIndex;

    std::map<double, std::vector<int> > m_gpaIndex;

    std::map<std::string, std::vector<int> > m_nameIndex;

    std::map<std::string, std::vector<int> > m_cityIndex;

    std::map<std::string, std::vector<int> > m_countryIndex;

 

    CStudents(const char *filename)

    {

        strcpy(m_fileName, filename);

        ReadRecords();

    }

 

    void SimulateRecords()

    {

        char name[24];

        char city[24];

        char country[24];

        int age;

        double gpa;

 

        static const char*arrCity[] = { "San Jose", "Iselin", "Madras", "New York", "Hyderabad", "Delhi", "Houston", "Seatle", "Wahsington", "Mumbai", "Pune", "Bangalore" };

        static const char*arrCountry[] = { "USA", "USA", "India", "USA", "India", "India", "USA""USA", "USA", "India", "India", "India" };

 

        CTime t = CTime::GetCurrentTime();

        srand(t.GetSecond());

        for(int i = 0; i < 250; i++)

        {

            CStudent s;

 

            s.m_name[0] = 'A' + (rand() % 26);

            s.m_name[1] = 'A' + (rand() % 26);

            s.m_name[2] = 'A' + (rand() % 26);

            s.m_name[3] = 'A' + (rand() % 26);

            s.m_name[4] = 'A' + (rand() % 26);

            s.m_name[5] = '\0';

            s.m_age = 15 + (rand() % 8);

            s.m_mark_gpa = 2 + (((rand() % 300)) / 100.0);

            int pos = (rand() % 11);

            strcpy(s.m_city, arrCity[pos]);

            strcpy(s.m_country, arrCountry[pos]);

            m_studList.push_back(s);

            WriteRecords(false);

        }

        ReadRecords();

    }

 

    void AddRecord(CStudent &s)

    {

        m_studList.push_back(s);

        WriteRecords();

    }

 

    void AddRecord(const char *name, int age, const char *country, char *city, double gpa)

    {

        CStudent s;

        strcpy(s.m_name,name);

        strcpy(s.m_city,city);

        strcpy(s.m_country,country);

        s.m_age = age;

        s.m_mark_gpa = gpa;

        m_studList.push_back(s);

        WriteRecords();

    }

 

    int ReadRecords()

    {

        FILE *istream = fopen(m_fileName, "rb");

    

        if (istream == 0)

            return false;

 

        m_studList.clear();

        m_ageIndex.clear();

        m_gpaIndex.clear();

        m_nameIndex.clear();

        m_cityIndex.clear();

        m_countryIndex.clear();

 

        char buf[4096];

 

        for(int i = 0; ; i++)

        {

            if(feof(istream))

                break;

            int nBytesRead = fread(buf, 1, sizeof(CStudent), istream);

            if(nBytesRead < sizeof(CStudent))

                break;

            CStudent s;

            char *p = reinterpret_cast<char*>(&s);

            memcpy(p, buf, sizeof(CStudent));

            m_studList.push_back(s);

            int pos = m_studList.size() - 1;

 

            m_ageIndex[s.m_age].push_back(pos);

            m_gpaIndex[s.m_mark_gpa].push_back(pos);

            m_nameIndex[s.m_name].push_back(pos);

            m_cityIndex[s.m_city].push_back(pos);

            m_countryIndex[s.m_country].push_back(pos);

        }

       

        fclose(istream);

 

        return m_studList.size();

    }

 

    int WriteRecords(bool bReload = true)

    {

        FILE *ostream = fopen(m_fileName, "wb");

 

        if (ostream == 0)

            return false;

 

        int nTotalRecordsWritten = 0;

        char buf[4096];

        for(int i = 0; i < m_studList.size(); i++)

        {

            const CStudent &s = m_studList[i];

            fwrite((const char*)&s, 1, sizeof(CStudent), ostream);

            nTotalRecordsWritten++;

        }

 

        fclose(ostream);

 

        if(bReload == true)

            ReadRecords();

        return nTotalRecordsWritten;

    }

};

 

extern CStudents theStudents;

 

 

//StudentData.CPP

 

#include "stdafx.h"

#include "studentdata.h"

 

 

CStudents theStudents("c:\\kathir.bin");

 

 

 

// StudentInformationSystemDlg.cpp : implementation file

//

 

#include "stdafx.h"

#include "StudentInformationSystem.h"

#include "StudentInformationSystemDlg.h"

#include "StudentData.h"

#include "StudentEditDlg.h"

 

CStudentInformationSystemDlg::CStudentInformationSystemDlg(CWnd* pParent /*=NULL*/)

      : CDialog(CStudentInformationSystemDlg::IDD, pParent)

    , m_valueText(_T(""))

    , m_keyText(_T(""))

{

      m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);

    m_searchIndex = 0;

}

 

void CStudentInformationSystemDlg::DoDataExchange(CDataExchange* pDX)

{

    CDialog::DoDataExchange(pDX);

    DDX_Control(pDX, IDC_LIST1, m_listCtrl);

    DDX_Control(pDX, IDC_KEY_COMBO, m_keyCtrl);

    DDX_Control(pDX, IDC_VALUE_COMBO, m_valueCtrl);

    DDX_CBString(pDX, IDC_VALUE_COMBO, m_valueText);

    DDX_CBString(pDX, IDC_KEY_COMBO, m_keyText);

}

 

BEGIN_MESSAGE_MAP(CStudentInformationSystemDlg, CDialog)

      ON_WM_SYSCOMMAND()

      ON_WM_PAINT()

      ON_WM_QUERYDRAGICON()

      //}}AFX_MSG_MAP

    ON_BN_CLICKED(IDOK, &CStudentInformationSystemDlg::OnBnClickedOk)

    ON_BN_CLICKED(IDCANCEL, &CStudentInformationSystemDlg::OnBnClickedCancel)

    ON_BN_CLICKED(IDC_SIMULATE, &CStudentInformationSystemDlg::OnBnClickedSimulate)

    ON_CBN_SELCHANGE(IDC_KEY_COMBO, &CStudentInformationSystemDlg::OnCbnSelchangeKeyCombo)

    ON_CBN_SELCHANGE(IDC_VALUE_COMBO, &CStudentInformationSystemDlg::OnCbnSelchangeValueCombo)

    ON_BN_CLICKED(IDC_ADD, &CStudentInformationSystemDlg::OnBnClickedAdd)

    ON_BN_CLICKED(IDC_EDIT, &CStudentInformationSystemDlg::OnBnClickedEdit)

    ON_BN_CLICKED(IDC_DELETE, &CStudentInformationSystemDlg::OnBnClickedDelete)

    ON_BN_CLICKED(IDC_DELETE_ALL, &CStudentInformationSystemDlg::OnBnClickedDeleteAll)

    ON_NOTIFY(HDN_ITEMDBLCLICK, 0, &CStudentInformationSystemDlg::OnHdnItemdblclickList1)

    ON_NOTIFY(NM_DBLCLK, IDC_LIST1, &CStudentInformationSystemDlg::OnNMDblclkList1)

END_MESSAGE_MAP()

 

static void AddData(CListCtrl &ctrl, int row, int col, const char *str)

{

    LVITEM lv;

    lv.iItem = row;

    lv.iSubItem = col;

    lv.pszText = (LPSTR) str;

    lv.mask = LVIF_TEXT;

    if(col == 0)

        ctrl.InsertItem(&lv);

    else

        ctrl.SetItem(&lv);

   

}

 

// CStudentInformationSystemDlg message handlers

 

BOOL CStudentInformationSystemDlg::OnInitDialog()

{

      CDialog::OnInitDialog();

 

      // Add "About..." menu item to system menu.

 

      // IDM_ABOUTBOX must be in the system command range.

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

            }

      }

 

      // Set the icon for this dialog.  The framework does this automatically

      //  when the application's main window is not a dialog

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

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

 

    m_listCtrl.InsertColumn(0, "No");

    m_listCtrl.SetColumnWidth(0, 50);

 

    m_listCtrl.InsertColumn(1, "Name");

    m_listCtrl.SetColumnWidth(1, 80);

   

    m_listCtrl.InsertColumn(2, "Age");

    m_listCtrl.SetColumnWidth(2, 50);

 

    m_listCtrl.InsertColumn(3, "City");

    m_listCtrl.SetColumnWidth(3, 70);

   

    m_listCtrl.InsertColumn(4, "Country");

    m_listCtrl.SetColumnWidth(4, 60);

   

    m_listCtrl.InsertColumn(5, "GPA");

    m_listCtrl.SetColumnWidth(5, 50);

 

    RefreshData();

   

 

      return TRUE;  // return TRUE  unless you set the focus to a control

}

 

void CStudentInformationSystemDlg::RefreshData()

{

    while(m_keyCtrl.GetCount() > 0)

        m_keyCtrl.DeleteString(0);

    m_keyCtrl.Clear();

 

    while(m_valueCtrl.GetCount() > 0)

        m_valueCtrl.DeleteString(0);

 

    m_valueCtrl.Clear();

 

    m_keyCtrl.AddString("All");

    m_keyCtrl.AddString("Name");

    m_keyCtrl.AddString("Age");

    m_keyCtrl.AddString("City");

    m_keyCtrl.AddString("Country");

    m_keyCtrl.AddString("GPA");

    m_keyCtrl.SetCurSel(0);

    m_searchIndex = 0;

    ShowData();

}

 

void CStudentInformationSystemDlg::DisplayStudent(int recpos, int winpos)

{

    char buf[32];

    const CStudent &s = theStudents.m_studList[recpos];

    sprintf(buf, "%d", recpos + 1);

    AddData(m_listCtrl, winpos, 0, buf);

    AddData(m_listCtrl, winpos, 1, s.m_name);

    sprintf(buf, "%d", s.m_age);

    AddData(m_listCtrl, winpos, 2, buf);

    AddData(m_listCtrl, winpos, 3, s.m_city);

    AddData(m_listCtrl, winpos, 4, s.m_country);

    sprintf(buf, "%.2lf", s.m_mark_gpa);

    AddData(m_listCtrl, winpos, 5, buf);

}

 

void CStudentInformationSystemDlg::ShowData()

{

    m_listCtrl.DeleteAllItems();

    if(m_searchIndex == 0)

    {

        for(int i = 0; i < theStudents.m_studList.size(); i++)

        {

            DisplayStudent(i,i);

        }

    }

    else if(m_searchIndex == 1)

    {

        std::string key = (const char*) m_valueText;

        std::vector<int> list = theStudents.m_nameIndex[key];

        for(int i = 0; i < list.size(); i++)

        {

            DisplayStudent(list[i],i);

        }

    }

    else if(m_searchIndex == 2)

    {

        std::string key = (const char*) m_valueText;

        std::vector<int> list = theStudents.m_cityIndex[key];

        for(int i = 0; i < list.size(); i++)

            DisplayStudent(list[i],i);

    }

    else if(m_searchIndex == 3)

    {

        std::string key = (const char*) m_valueText;

        std::vector<int> list = theStudents.m_countryIndex[key];

        for(int i = 0; i < list.size(); i++)

            DisplayStudent(list[i],i);

    }

    else if(m_searchIndex == 4)

    {

        int key = atoi(m_valueText);

        std::vector<int> list = theStudents.m_ageIndex[key];

        for(int i = 0; i < list.size(); i++)

            DisplayStudent(list[i],i);

    }

    else if(m_searchIndex == 5)

    {

        double key = atof(m_valueText);

        std::vector<int> list = theStudents.m_gpaIndex[key];

        for(int i = 0; i < list.size(); i++)

            DisplayStudent(list[i],i);

    }

}

 

 

void CStudentInformationSystemDlg::OnSysCommand(UINT nID, LPARAM lParam)

{

      if ((nID & 0xFFF0) == IDM_ABOUTBOX)

      {

            CAboutDlg dlgAbout;

            dlgAbout.DoModal();

      }

      else

      {

            CDialog::OnSysCommand(nID, lParam);

      }

}

 

// If you add a minimize button to your dialog, you will need the code below

//  to draw the icon.  For MFC applications using the document/view model,

//  this is automatically done for you by the framework.

 

void CStudentInformationSystemDlg::OnPaint()

{

      if (IsIconic())

      {

            CPaintDC dc(this); // device context for painting

 

            SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0);

 

            // Center icon in client rectangle

            int cxIcon = GetSystemMetrics(SM_CXICON);

            int cyIcon = GetSystemMetrics(SM_CYICON);

            CRect rect;

            GetClientRect(&rect);

            int x = (rect.Width() - cxIcon + 1) / 2;

            int y = (rect.Height() - cyIcon + 1) / 2;

 

            // Draw the icon

            dc.DrawIcon(x, y, m_hIcon);

      }

      else

      {

            CDialog::OnPaint();

      }

}

 

// The system calls this function to obtain the cursor to display while the user drags

//  the minimized window.

HCURSOR CStudentInformationSystemDlg::OnQueryDragIcon()

{

      return static_cast<HCURSOR>(m_hIcon);

}

 

 

void CStudentInformationSystemDlg::OnBnClickedCancel()

{

    // TODO: Add your control notification handler code here

    OnCancel();

}

 

void CStudentInformationSystemDlg::OnBnClickedOk()

{

    ShellExecute(NULL, _T("open"), _T("http://www.softwareandfinance.com"),

                NULL, NULL, SW_SHOWNORMAL);   

    OnCancel();

}

 

void CStudentInformationSystemDlg::OnBnClickedSimulate()

{

    theStudents.SimulateRecords();

    RefreshData();

}

 

void CStudentInformationSystemDlg::OnCbnSelchangeKeyCombo()

{

    UpdateData(TRUE);

    m_valueCtrl.Clear();

    m_listCtrl.DeleteAllItems();

    while(m_valueCtrl.GetCount() > 0)

        m_valueCtrl.DeleteString(0);

 

    if( m_keyText.Compare("All") == 0)

    {

        m_searchIndex = 0;

    }

    else if( m_keyText.Compare("Name") == 0)

    {

        m_searchIndex = 1;

        for(std::map<std::string, std::vector<int> >::iterator it = theStudents.m_nameIndex.begin(); it != theStudents.m_nameIndex.end(); ++it)

        {

            m_valueCtrl.AddString(it->first.c_str());

        }

    }

    else if( m_keyText.Compare("City") == 0)

    {

        m_searchIndex = 2;

        for(std::map<std::string, std::vector<int> >::iterator it = theStudents.m_cityIndex.begin(); it != theStudents.m_cityIndex.end(); ++it)

        {

 

            m_valueCtrl.AddString(it->first.c_str());

        }

    }

    else if( m_keyText.Compare("Country") == 0)

    {

        m_searchIndex = 3;

        for(std::map<std::string, std::vector<int> >::iterator it = theStudents.m_countryIndex.begin(); it != theStudents.m_countryIndex.end(); ++it)

        {

 

            m_valueCtrl.AddString(it->first.c_str());

        }

    }

    else if( m_keyText.Compare("Age") == 0)

{

        m_searchIndex = 4;

        for(std::map<int, std::vector<int> >::iterator it = theStudents.m_ageIndex.begin(); it != theStudents.m_ageIndex.end(); ++it)

        {

            char buf[32];

            sprintf(buf,"%d", it->first);

            m_valueCtrl.AddString(buf);

        }

    }

    else if( m_keyText.Compare("GPA") == 0)

    {

        m_searchIndex = 5;

        for(std::map<double, std::vector<int> >::iterator it = theStudents.m_gpaIndex.begin(); it != theStudents.m_gpaIndex.end(); ++it)

        {

            char buf[32];

            sprintf(buf,"%.2lf", it->first);

            m_valueCtrl.AddString(buf);

        }

    }

    ShowData();

}

 

 

void CStudentInformationSystemDlg::OnCbnSelchangeValueCombo()

{

    UpdateData(TRUE);

    ShowData();

}

 

 

void CStudentInformationSystemDlg::OnBnClickedAdd()

{  

    CStudent s;

    CStudentEditDlg dlg(s, false);

    if( dlg.DoModal() == IDOK)

    {

        theStudents.AddRecord(s);

        ShowData();

    }

}

 

void CStudentInformationSystemDlg::OnBnClickedEdit()

{  

    POSITION pos = m_listCtrl.GetFirstSelectedItemPosition();

    if (pos != NULL)

    {

       while (pos)

       {

          int nItem = m_listCtrl.GetNextSelectedItem(pos);

          int idx = atoi(m_listCtrl.GetItemText(nItem, 0)) - 1;

 

          CStudent &s = theStudents.m_studList[idx];

          CStudentEditDlg dlg(s, true);

          if( dlg.DoModal() == IDOK)

          {

              theStudents.WriteRecords();

              ShowData();

          }

       }

    }

}

 

void CStudentInformationSystemDlg::OnBnClickedDelete()

{  

    POSITION pos = m_listCtrl.GetFirstSelectedItemPosition();

    if (pos != NULL)

    {

       while (pos)

       {

          int nItem = m_listCtrl.GetNextSelectedItem(pos);

          int idx = atoi(m_listCtrl.GetItemText(nItem, 0)) - 1;

 

          int ptr = 0;

          for(std::vector<CStudent>::iterator it = theStudents.m_studList.begin(); it != theStudents.m_studList.end(); ++it)

          {

              if(ptr == idx)

              {

                  theStudents.m_studList.erase(it);

                  break;

              }

              ptr++;

          }

          theStudents.WriteRecords();

          ShowData();

       }

    }

}

 

void CStudentInformationSystemDlg::OnBnClickedDeleteAll()

{

    theStudents.m_studList.clear();

    theStudents.WriteRecords();

    RefreshData();

}

 

void CStudentInformationSystemDlg::OnHdnItemdblclickList1(NMHDR *pNMHDR, LRESULT *pResult)

{

    LPNMHEADER phdr = reinterpret_cast<LPNMHEADER>(pNMHDR);

    

    *pResult = 0;

}

 

void CStudentInformationSystemDlg::OnNMDblclkList1(NMHDR *pNMHDR, LRESULT *pResult)

{

    OnBnClickedEdit();  

    *pResult = 0;

}

 

 

Click here to download the VS 2005 Project file and executable

 

Output