Click here to Skip to main content
15,892,674 members
Articles / Desktop Programming / MFC

A Class to Save and Load Listbox Data

Rate me:
Please Sign up or sign in to vote.
3.91/5 (13 votes)
2 Jan 20021 min read 173.7K   2.2K   44  
CListBoxSafe is a class that can save data from a listbox to file and load data from a file into a listbox.
// ListBoxSafe.cpp: implementation of the CListBoxSafe class.
//
//////////////////////////////////////////////////////////////////////

#include "stdafx.h"
#include "ListBoxSafe.h"

#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[]=__FILE__;
#define new DEBUG_NEW
#endif


//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////

CListBoxSafe::CListBoxSafe()
{

}

CListBoxSafe::~CListBoxSafe()
{

}

void CListBoxSafe::SaveList(CListBox &list, CString FileName, int MaxItems, int MaxItemLen)
{
int count = list.GetCount();
CString *pData = new CString[count];
CFile sav;

// Default values
if(MaxItems==0)
{
	MaxItems = 999;
}
if(MaxItemLen==0)
{
	MaxItemLen = 30;
}


if (sav.Open(FileName, CFile::modeCreate + CFile::modeWrite))
{		

for(int i=0;i<=count-1;i++)
{
list.GetText(i,pData[i]);
sav.Seek((long)(i*MaxItemLen),CFile::begin);
sav.Write(pData[i],pData[i].GetLength());
}
	
}	

}

void CListBoxSafe::LoadList(CListBox &ListToFill, CString FileName, int MaxItems, int ItemLen)
{
// Default values
if(MaxItems==0)
{
	MaxItems = 999;
}
if(ItemLen==0)
{
	ItemLen = 30;
}

	
CString *pData = new CString[MaxItems];
CFile loa;
TCHAR *temp = new TCHAR[ItemLen];
int Bytes = 0;

if (loa.Open(FileName, CFile::modeRead))
{		
for(int i=0;i<=MaxItems;i++)
{
	loa.Seek((long)(i*ItemLen),CFile::begin);
	Bytes = loa.Read(temp,ItemLen);
	temp[Bytes] = NULL;
	pData[i] = temp;
	pData[i].TrimRight();
	if(pData[i]!="")
	{
	ListToFill.AddString(LPCTSTR(pData[i]));
	}
	else
	{
		return;
	}
}

}
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.


Written By
Belgium Belgium
bla bla bla

Comments and Discussions