You are on page 1of 23

Chng By - Dng List Controls

C hai loi List controls dng trong VB6. l Listbox v Combobox. C hai u display mt s hng ta c th la chn. Listbox chim mt khung ch nht, nu chiu ngang nh th c khi khng display y mt hng, nu chiu di khng display tt c mi hng th Listbox t ng cho ta mt vertical scroll bar cho bit cn c nhiu hng b che v ta c th xem cc hng y bng cch dng vertical scroll bar. Combobox thng thng ch display mt hng, nhng ta c th chn display bt c hng no khc. Combobox ging nh mt tp hp ca mt Textbox nm pha trn v mt Listbox nm pha di.

Listbox c rt nhiu cng dng v n rt uyn chuyn. Trong chng ny ta s hc qua cc p dng sau ca Listbox:

Display nhiu s la chn User selects bng cch click hay drag-drop Nhng cch dng Property Sorted Cch dng Multiselect Dng display Events Dng Search hay process text Cch dng Itemdata song song vi cc Items ca List Dng lm Queue

Listbox Display nhiu s la chn Ta hy bt u vit mt chng trnh gm c mt Listbox tn lstNames nm trong mt Form. Trong lstNames ta nh vo tn ca by ngi, mi ln xung hng nh nh Ctrl-Enter, thay v ch Enter, nu khng VB6 tng ta nh xong nn close property List. Cc tn ny l nhng hng s hin ra trong Listbox khi ta bt u chy program.

Ngoi lstNames ta cho thm mt Label vi Caption STUDENTS trang hong, v mt Label khc tn lblName. Mi khi User click ln hng tn no ta mun display hng tn y trong lblName. Sau cng ta cho vo mt CommandButton tn CmdExit cho User phng tin Stop ci program. Ta s c chng trnh nh sau: Private Sub lstNames_Click() ' Assign the selected line of Listbox lstNames to Caption of Label lblName lblName.Caption = lstNames.List(lstNames.ListIndex) ' or = lstNames.text End Sub Private Sub CmdExit_Click() End End Sub Gi s ta click vo tn John Smith trn Listbox, ta s thy tn y cng uc display trong Label lblName.

Trong th d ny, Listbox lstNames c 7 hng ( Items). Con s Items ny l Property ListCount ca Listbox. Cc Items ca Listbox c m t 0 n ListCount-1. Trong trng hp ny l t 0 n 6. Khi User click ln mt hng, Listbox s generate Event lstNames_Click. Lc by gi ta c th bit
2

c User va mi Click hng no bng cch hi Property ListIndex ca lstNames, n s c value t 0 n ListCount-1. Lc program mi chy, cha ai Click ln Item no ca Listbox th ListIndex = -1. Nhng Items trong Listbox c xem nh mt Array ca String. Array ny c gi l List. Do , ta ni n Item th nht ca Listbox lstNames bng cch vit lstNames.List(0) , v tng t nh vy, Item cui cng l lstNames.List( lstNames.ListCount-1). Ta c th ni n item va c Clicked bng hai cch: hoc l lstNames.List(lstNames.ListIndex), hoc l lstNames.text. Save content ca Listbox By gi lu tr content ca lstNames, ta thm mt CommandButton tn CmdSave. Ta s vit code khi User click nt CmdSave program s m mt Output text file v vit mi items ca lstNames vo : Private Sub CmdSave_Click() Dim i, FileName, FileNumber ' Obtain Folder where this program's EXE file resides FileName = App.Path ' Make sure FileName ends with a backslash If Right(FileName, 1) <> "\" Then FileName = FileName & "\" FileName = FileName & "MyList.txt" ' name output text file MyList.txt ' Obtain an available filenumber from the operating system FileNumber = FreeFile ' Open the FileName as an output file , using FileNumber as FileHandle Open FileName For Output As FileNumber ' Now iterate through each item of lstNames For i = 0 To lstNames.ListCount - 1 ' Write the List item to file. Make sure you use symbol # in front of FileNumber Print #FileNumber, lstNames.List(i) Next Close FileNumber ' Close the output file End Sub App l mt Object c bit i din cho chnh ci program ang chy. y ta dng Property Path bit lc program ang chy th execute module EXE ca n nm u. L do l thng thng ta cc files lin h cn thit cho program ln qun hoc ngay trong folder ca program hay trong mt subfolder, chng hn nh data, logs, .v.v.. App cn c mt s Properties khc cng rt hu dng nh PrevInstance, Title, Revision ..v.v. Nu mi started mt program m thy App.PrevInstance = True th lc by gi cng c mt copy khc ca program ang chy. Nu cn ta End program ny trnh chy 2 copies ca program cng mt lc. App.Title v App.Revision cho ta tin tc v Title v Revision ca program ang chy. vit ra mt Text file ta cn phi Open n trong mode Output v tuyn b t ry tr i s dng mt con s (FileNumber) i din ci File thay v dng chnh FileName. trnh dng mt FileNumber hin hu, tt nht ta hi xin Operating System cung cp cho mnh mt con s cha ai dng bng cch gi Function FreeFile. Con s FileNumber ny cn uc gi l FileHandle (Handle l tay cm). Sau khi ta Close FileNumber con s ny tr nn FREE v Operating System s c th dng n li. Do bn phi trnh gi FreeFile lin tip hai ln, v OS s cho bn cng mt con s. Tc l, sau khi gi FreeFile phi dng n ngay bng cch Open mt File ri mi gi FreeFile ln k c mt con s khc. cch dng ch Input, Output cho files l relative (tng i) vi v tr ca program (n nm trong
3

memory ca computer). Do t trong memory vit ra hard disk th ni l Output. Ngc li c t mt Text file nm trn hard disk vo memory cho program ta th gi l Input. Load mt Text file vo Listbox Trong bi ny, thay v nh cc Items ca Listbox vo Property List ca lstNames ta c th populate (lm y) lstNames bng cch c cc Items t mt Text file. Ta th thm mt CommandButton tn CmdLoad. Ta s vit code khi User click nt CmdLoad program s m mt Input text file v c tng hng b vo lstNames: Private Sub CmdLoad_Click() Dim i, FileName, FileNumber, anItem ' Obtain Folder where this program's EXE file resides FileName = App.Path ' Make sure FileName ends with a backslash If Right(FileName, 1) <> "\" Then FileName = FileName & "\" FileName = FileName & "MyList.txt" ' Obtain an available filenumber from the operating system FileNumber = FreeFile ' Open the FileName as an input file , using FileNumber as FileHandle Open FileName For Input As FileNumber lstNames.Clear ' Clear the Listbox first ' Now read each line until reaching End-Of-File, i.e. no more data Do While NOT EOF(FileNumber) Line Input #FileNumber, anItem ' Read a line from the Text file into variable anItem lstNames.AddItem anItem ' Add this item to the bottom of lstNames Loop Close FileNumber ' Close the input file End Sub c t mt Text file ta cn phi Open n trong mode Input. Trc khi populate lstNames ta cn phi delete tt c mi items c sn bn trong. thc hin vic ta dng method Clear ca Listbox. Sau ta dng method AddItem cho thm tng hng vo trong Listbox. By default, nu ta khng ni nht vo ch hng no th AddItem nht Item mi vo di cht ca Listbox. Nu mun nht hng mi vo ngay trc item th 5 (ListIndex = 4), ta vit: lstNames.AddItem newItemString, 4 ' newItemString contains "Ross Close", for example ' To insert a new Item at the beginning of the Listbox, write: lstNames.AddItem newItemString, 0 Nh l mi ln bn Add mt Item vo Listbox th ListCount ca Listbox increment by 1. Mun delete mt item t Listbox ta dng method RemoveItem, th d nh mun delete item th ba (ListIndex=2) ca lstNames, ta vit: lstNames.RemoveItem 2 Mi ln bn RemoveItem t Listbox the ListCount ca Listbox decrement by 1. Do nu bn dng ci Test da vo ListCount ca mt ListBox nhy ra khi mt Loop th phi coi chng trnh lm cho value ListCount thay i trong Loop v AddItem hay RemoveItem.
4

Ta c tng hng ca mt Text file bng cch dng Line Input #FileNumber. Khi c n cui File, system d cho ta value EOF(FileNumber) = True. Ta dng value y cho program nhy ra khi While.. Loop. Cu Do While NOT EOF(FileNumber) c ngha Trong khi cha n End-Of-File ca Text File i din bi FileNumber th c t hng v b vo Listbox. Ging nh "Trong khi cha tr ht n nh v th phi tip tc r". Drag-Drop Ta hc qua Click Event ca Listbox. By gi dng Drag-Drop cho Listbox bn hy t 2 Labels mi ln Form. Ci th nht tn g cng c nhng c Caption l Room A. Hy gi Label th hai l lblRoom v cho Property BorderStyle ca n bng Fixed Single. K n select c hai Labels (Click a Label then hold down key Ctrl while clicking the second Label) ri click copy v paste ln Form. VB6 s cho bn Array ca hai lblRoom labels. cho lstNames mt DragIcon, bn click lstNames, click Property DragIcon pop-up mt dialog cho bn chn mt dragdrop icon t folder C:\Program Files\Microsoft Visual Studio\Common\Graphics\Icons\Dragdrop, chng hn nh DRAG2PG.ICO:

Ta s dng Event MouseDown ca lstNames pop-up DragIcon hnh 2 trang giy cho User Drag n qua bn phi ri b xung ln mt trong hai lblRoom. Khi DragIcon ri ln lblRoom, lblRoom s generate Event DragDrop. Ta s dng Event DragDrop ny assign property Text ca Source (tc l lstNames, ci control t n pht xut Drag action) vo Property Caption ca lblRoom. Lu v y ta dng cng mt tn cho c hai lblRoom nn ch cn vit code mt ch handle Event DragDrop. Private Sub lstNames_MouseDown(Button As Integer, Shift As Integer, X As Single, Y As Single) ' Start Pop-up DragIcon and start Drag action lstNames.Drag End Sub Private Sub lblRoom_DragDrop(Index As Integer, Source As Control, X As Single, Y As Single) ' Assign Property Text of Source (i.e. lstNames) to Label's Caption lblRoom(Index).Caption = Source.Text End Sub Kt qu sau khi Drag hai tn t Listbox qua Labels l nh sau:

Dng Property Sorted

Trong th d trn ta c th quyt nh v tr ca mt Item mi khi ta nht n vo Listbox. i khi ta mun cc Items ca Listbox c t ng sp theo th t Alphabet. Bn c th set Property Sorted = True thc hin chuyn ny. C mt gii hn l bn phi cho Property Sorted mt value (True hay False) trong lc design, ch trong khi chy program bn khng th lm cho Property Sorted ca Listbox thay i. Gi d ta mun sort cc Items ca mt Listbox khi cn. Vy th ta lm sao? Gii php rt n gin. Bn to mt Listbox tn lstTemp chng hn. Cho n Property Visible= False ( khng ai thy n) v Property Sorted=True. Khi cn sort lstNames chng hn, ta copy content ca lstNames b vo lstTemp, on Clear lstNames ri copy content ( c sorted) ca lstTemp tr li lstNames. Lu l ta c th AddItem vo mt Listbox vi Property Sorted=True, nhng khng th xc nh nht Item vo trc hng no, v v tr ca cc Items do Listbox quyt nh khi n sort cc Items. Ta hy cho thm vo Form mt CommandButton mi tn CmdSort v vit code cho Event Click ca n nh sau: Private Sub CmdSort_Click() Dim i lstTemp.Clear ' Clear temporary Listbox ' Iterate though every item of lstNames For i = 0 To lstNames.ListCount - 1 ' Add the lstNames item to lstTemp lstTemp.AddItem lstNames.List(i) Next lstNames.Clear ' Clear lstNames ' Iterate though every item of lstTemp For i = 0 To lstTemp.ListCount - 1 ' Add the lstTemp item to lstNames lstNames.AddItem lstTemp.List(i) Next lstTemp.Clear ' Tidy up - clear temporary Listbox End Sub Nhn tin, ta mun c option sort cc tn theo FirstName hay Surname. Vic ny hi rc ri hn mt cht, nhng nguyn tc vn l dng ci sorted Listbox v hnh tn lstTemp. Bn hy t ln pha trn lstName hai cl Labels mi tn lblFirstName v lblSurName v cho chng
6

Caption "FirstName" v "SurName". T y ta Load file "MyList.txt" vo lstNames bng cch Click button CmdLoad ch khng Edit Property List ca lstNames enter Items lc design na. Ngoi ra ta dng du phy (,) tch FirstName khi SurName trong mi tn cha trong file MyList.txt. Content ca file MyList.txt by gi tr thnh nh sau: Peter,Jones Kevin,White Sue,Rose John,Smith Trevor,Kennedy Alan,Wright Ron,Bruno Ta s sa code trong Sub CmdLoad_Click li khi nht tn vo lstNames, FirstName v SurName mi th chim 10 characters. cc ch trong Items ca lstNames sp hng ngay ngn ta i Font ca lstNames ra Courier New. Courier New l mt loi Font m chiu ngang ca ch m bng ch i, trong khi hu ht cc Fonts khc nh Arial, Times Roman ..v.v. l Proportional Spacing, c ngha l ch m rng hn ch i. Listing mi ca Sub CmdLoad_Click tr thnh nh sau: Private Sub CmdLoad_Click() Dim i, Pos Dim FileName, FileNumber, anItem Dim sFirstName As String * 10 ' fixed length string of 10 characters Dim sSurName As String * 10 ' fixed length string of 10 characters ' Obtain Folder where this program's EXE file resides FileName = App.Path ' Make sure FileName ends with a backslash If Right(FileName, 1) <> "\" Then FileName = FileName & "\" FileName = FileName & "MyList.txt" ' Obtain an available filenumber from the operating system FileNumber = FreeFile ' Open the FileName as an input file , using FileNumber as FileHandle Open FileName For Input As FileNumber lstNames.Clear ' Clear the Listbox first ' Now read each line until reaching End-Of-File, i.e. no more data Do While Not EOF(FileNumber) Line Input #FileNumber, anItem ' Read a line from the Text file ' Now separate FirstName from SurName Pos = InStr(anItem, ",") ' Locate the comma "," ' The part before "," is FirstName sFirstName = Left(anItem, Pos - 1) sFirstName = Trim(sFirstName) ' Trim off any unwanted blank spaces ' The part after "," is SurName sSurName = Mid(anItem, Pos + 1)
7

sSurName = Trim(sSurName) ' Trim off any unwanted blank spaces lstNames.AddItem sFirstName & sSurName ' Add this item to the bottom of lstNames Loop Close FileNumber ' Close the input file End Sub V FirstName nm bn tri ca mi Item nn sort theo FirstName cng ging nh sort c Item. Vic y ta lm bng Sub CmdSort_Click ri, do khi User click Label lblFirstName ta ch cn gi CmdSort_Click nh sau: Private Sub lblFirstName_Click() CmdSort_Click End Sub sort theo SurName ta cn phi tm thi SurName qua bn tri ca Item trc khi b vo lstTemp. Ta thc hin chuyn ny bng cch hon chuyn v tr ca FirstName v SurName trong Item trc khi b vo lstTemp. Sau , khi copy cc Items t lstTemp b v li lstNames ta li nh hon chuyn FirstName v SurName chng nm ng li v tr. Tc l, ci mnh ca ta l mun bit Item no phi nm u trong lstNames, ch d nhin khi display mi Item u c FisrtName bn tri. Code sort tn theo SurName cng ging nh CmdSort_Add nhng thm tht cht t nh sau: Private Sub lblSurName_Click() Dim i, anItem Dim sFirstName As String * 10 ' fixed length string of 10 characters Dim sSurName As String * 10 ' fixed length string of 10 characters lstTemp.Clear ' Clear temporary Listbox ' Iterate though every item of lstNames For i = 0 To lstNames.ListCount - 1 anItem = lstNames.List(i) ' Identify FistName and SurName sFirstName = Left(anItem, 10) sSurName = Mid(anItem, 11) ' Swap FirstName/SurName positions before adding to lstTemp lstTemp.AddItem sSurName & sFirstName Next lstNames.Clear ' Clear lstNames ' Iterate though every item of lstTemp For i = 0 To lstTemp.ListCount - 1 anItem = lstTemp.List(i) ' Identify FistName and SurName sSurName = Left(anItem, 10) ' SurName now is on the left sFirstName = Mid(anItem, 11) ' Add FirstName/SurName in correct positions to lstNames lstNames.AddItem sFirstName & sSurName Next lstTemp.Clear ' Tidy up - clear temporary Listbox
8

End Sub Cc Items trong lstNames sorted theo SurName hin ra nh sau:

Nhn tin y ta sa ci Sub CmdSave_Click li mt cht Save Items theo sorted order mi nu cn: Private Sub CmdSave_Click() Dim i, FileName, FileNumber, anItem ' Obtain Folder where this program's EXE file resides FileName = App.Path ' Make sure FileName ends with a backslash If Right(FileName, 1) <> "\" Then FileName = FileName & "\" ' Call Output filename "MyList.txt" FileName = FileName & "MyList.txt" ' Obtain an available filenumber from the operating system FileNumber = FreeFile ' Open the FileName as an output file , using FileNumber as FileHandle Open FileName For Output As FileNumber ' Now iterate through each item of lstNames For i = 0 To lstNames.ListCount - 1 anItem = lstNames.List(i) anItem = Trim(Left(anItem, 10)) & "," & Trim(Mid(anItem, 11)) ' Write the List item to file. Make sure you use symbol # in front of FileNumber Print #FileNumber, anItem Next Close FileNumber ' Close the output file End Sub Trong bi ti ta s hc thm cc p dng khc ca ListBox. Listbox Cch dng MultiSelect

Cho n gi User click vo Listbox chn ch mt Item. Khi mt Item c chn th hng y tr nn highlighted vi background mu xanh m. Nu k ta click mt hng khc th hng c c display tr li bnh thng v hng mi uc selected s tr nn highlighted. Listbox cho ta c th select nhiu Items cng mt lc bng cch set Property MultiSelect = Extended

i vi MultiSelected Listbox, ta chn mt nhm Items lin tc bng cch click Item u ri nhn nt Shift trong khi click Item cui. Ta cng c th tip tc Select/Deselect thm bng cch n nt Ctrl trong khi click cc Items. Nu ta click mt Item cha c selected th n s tr nn selected (highlighted mu xanh), nu ta click mt Item c selected ri th n s tr nn deselected (khng cn mu xanh na). Th d trong program bn click "Peter Jones", k n nt Shift trong khi click "Sue Rose", k bung nt Shift ra n nt Ctrl trong khi click "Kevin White", bn s c nhng selected Items nh trong hnh di y:

Ngoi ra bn cng c th MultiSelect nhiu Items trong mt Listbox bng cch dng mouse drag, tc l bn click ln Item u ri tip tc mousebutton trong khi ko mousepointer n Item cui cng mi bung mousebutton ra. Ci Bug c n By gi gi s ta mun delete tt c nhng Items va c selected (highlighted). Bn hy t mt CommandButton mi tn CmdDeleteSelectedItems vo Form. Ta s dng Event Click ca Button ny delete nhng selected Items. Mt selected Item ca lstNames s c property Selected ca n bng True. Tc l nu Item th ba (ListIndex=2) c selected th ta c lstNames.Selected(2) = True. Ta c nh s iterate through mi Items ca lstNames, xem Item no c selected th mnh s delete n bng cch dng method RemoveItem. Ta s vit code cho Sub CmdDeleteSelectedItems_Click() nh sau: Private Sub CmdDeleteSelectedItems_Click() Dim i
10

For i = 0 To lstNames.ListCount - 1 If lstNames.Selected(i) = True Then lstNames.RemoveItem i End If Next End Sub Bn hy chy chng trnh, click Load populate lstNames vi cc tn c t text file, ri MultiSelect cc tn nh trong hnh pha trn. K click button DeleteSelectedItems. Program s t (crash) v c hnh nh sau:

Nu bn click nt Debug, program s ngng ti dng code gp error v highlight n vi background mu vng. mousepointer ln trn ch i ca lstNames.Selected(i), VB6 s popup message nho nh i = 4.

Bn thy trong hnh lc ny lstNames ch cn c 4 Items (Ron, Trevor, John v Alan), v cc Items kia b removed. Bn c bit ti sao program crashed khng? l v program ang refer n property Selected ca Item th nm ( ArrayIndex i = 4) ca lstNames trong khi lstNames by gi ch cn c 4 Items. V vy program crashed vi message "Runtime error '381': Invalid property array index". Th phm ca ci Bug c n ny l statement For i = 0 To lstNames.ListCount - 1. VB6 ch tnh value ca lstNames.ListCount -1 mt ln lc khi s For..Loop m thi (tc l lstNames.ListCount -1 = 6), n khng lu l ListCount gim value mi ln mt Item b Removed. Ngoi ra ta thy tn "Trevor Kennedy" cng khng b removed, tc l n b lt s nu ta dng For..Loop theo cch ny. L do l sau khi ta Remove "Peter Jones" (Item th hai), "Trevor Kennedy" b y ln v tr thnh Item th hai mi. K ta increment value ca i thnh 2 ri process Item th ba, tc l "Sue Rose", nn "Trevor Kennedy" khng h c processed.
11

Sub CmdDeleteSelectedItems_Click cn phi c vit li dng While ... Loop, thay v For...Loop. Trong While...Loop, lstNames.ListCount - 1 c evaluated (tnh) test mi iteration. Khi no ta Remove mt Item th ta khng increment i, v Item ngay di removed Item c y ln. Listing mi nh sau: Private Sub CmdDeleteSelectedItems_Click() Dim i i = 0 ' Initialise value of i to start from first Item ' Note that lstNames.ListCount is evaluated freshly at each iteration Do While i <= (lstNames.ListCount - 1) If lstNames.Selected(i) = True Then lstNames.RemoveItem i ' No need to increment i here because the item below is pushed up Else i = i + 1 ' increment i to process the next item End If Loop End Sub Dng Listbox display Event Log Trong th d sau y ta mun display input t mt serial COM port ( c data tht qua serial COM port ta phi dng control MsCOMM c hnh telephone mu vng trong ToolBox). Nhng tin vic biu din, thay v c mt message t mt serial COM port, ta s emulate n bng cch dng mt ComboBox. Khi user select mt hng t ComboBox cboInput th ta xem cboInput.text nh data c t serial COM port. Lp tc lc y ta s display input message trong hai dng: ASCII v HEX. Mi hng input message c prefix vi ngy v gi trc khi c cho vo hai Listboxes lstASCII v lstHexadecimal. Hnh di y cho thy Form ang display trong ASCII mode.

Nu bn click button Display in HEX th caption ca button i thnh Display in ASCII, lstASCII tr nn v hnh v lstHexadecimal s hin ra nh sau:

12

Di y l listing ca Function HexDisplay convert t ASCII string ra Hexadecimal string. Function HexDisplay(InASCII) As String ' Convert an ASCII string to HEX string Dim InLen, i, msg, HexStr InLen = Len(InASCII) ' Get length of input string ' Convert each ASCII character to Hex For i = 1 To InLen HexStr = Hex(Asc(Mid(InASCII, i, 1))) ' If HEX has only one digit then prefix it with 0 If Len(HexStr) = 1 Then HexStr = "0" & HexStr msg = msg + HexStr & " " Next i HexDisplay = msg ' Return result string for Function End Function Trong program ny, khi Listbox t n 1000 items th mi ln mt hng mi c thm vo, hng c nht s b removed. cho hng mi nht khng b du ta phi nh cho ListIndex ca Listbox bng Listcount-1 Listbox t ng scrollup v highlight hng cui. Mi khi ta thm mt hng vo Listbox lstHexadecimal, ta cng ng thi vit n vo mt LogFile. Tn ca LogFile ny da vo ngy ly t Computer System v c dng nh Hex30Jun01.log. Tc l ta s dng mt LogFile khc cho mi ngy. Mi khi qua ngy mi, program t ng dng mt LogFile mi. Nh l khi mun vit vo mt text file theo tn g , nu file cha hin hu th ta phi create n v vit vo, nu file hin hu ri ta ch cn append hng mi vo cui file (phi cn thn ch ny, v nu khng, ta v overwrite ci file v mt ht nhng g n cha trc y). Sub DisplayInHEX(inString) Dim Mess, LogFileName ' Convert ASCII to Hex Mess = HexDisplay(inString) ' Prefix with date and time and add it to the bottom of Listbox lstHexadecimal.AddItem Format(Now, "dd/mm/yyyy hh:nn:ss") & " " & Mess ' Keep only the latest 1000 events If lstHexadecimal.ListCount >= 1000 Then ' Remove the first Item, i.e. the oldest item lstHexadecimal.RemoveItem 0 End If ' Highlight the lattest item in the Listbox
13

lstHexadecimal.ListIndex = lstHexadecimal.ListCount - 1 ' Use different log file each day. Filename has format like Hex15Jun01.log LogFileName = "Hex" & Format(Now, "ddmmmyy") & ".log" ' Log to file including Date and Time LogEvent LogFileName, Mess, False, 2 End Sub In ra content ca Listbox Di y l mt p dng ca Listbox MutiSelect in ra c Listbox hay ch nhng hng c selected. Sub PrintList nhn:

Listbox m ta mun in mt Boolean value m nu True th in c Listbox Title ca Printout

Sub PrintList(theList As ListBox, PrintAll as Boolean, Title As String) ' Print the whole lot or only selected lines in a listbox ' PrintAll = True means printing the whole content of the listbox Const MaxLinesPerPage = 50 Dim msg, i, j, PageNo, NumLines, HasSome, Margin HasSome = False ' Flag indicating existence of data Margin = Space(10) ' Make a margin of 5 characters Title = vbLf & vbLf & Title + vbCrLf & vbLf NumLines = 0 ' Init number of lines on this page PageNo = 1 ' init Page number msg = Title ' Msg will contain everything starting with Title Printer.FontName = "Courier New" ' Initialise Printer Fontname Printer.FontSize = 10 ' Initialise Printer FontSize Screen.MousePointer = vbHourglass ' Change mousepointer shape to Hourglass. If theList.ListCount > 0 Then ' get here if the listbox is not empty For i = 0 To theList.ListCount - 1 ' Go thru each line of text in the listbox If theList.Selected(i) Or PrintAll Then ' print a line of text if it's selected or PrinAll is true DoEvents ' Let other processes have a chance to run HasSome = True NumLines = NumLines + 1 ' Increment count of lines If Left(theList.List(i), 1) = "'" Then ' if first character is "'" then use this as an indication to force a new page If NumLines > 0 Then ' Add extra blank lines to make up a page before inserting page number
14

For j = NumLines - 1 To MaxLinesPerPage msg = msg & vbCrLf Next j ' Insert Page number at end of page msg = msg & Space$(35) & "Page-" & CStr(PageNo) Printer.Print msg Printer.NewPage ' Send new page. NumLines = 1 ' reset Number of lines, counting this current line PageNo = PageNo + 1 ' Increment Page number msg = Title ' Reset Msg to contain Title for new page ' Append this current line, ignoring character "'" msg = msg & Margin & Mid(theList.List(i), 2) & vbCrLf Else ' Blank page so far - so just appending this line, ignoring character "'" msg = msg & Margin & Mid(theList.List(i), 2) & vbCrLf End If Else ' Normal line - just keep appending it to Msg msg = msg + Margin & theList.List(i) & vbCrLf End If theList.Selected(i) = False ' Clear highlight of selected line, ie. deselect it If NumLines > MaxLinesPerPage Then ' Start new page if page already full If PageNo > 1 Then ' Insert page number at the bottom, except for first page msg = msg + vbCrLf & Space$(35) & "Page-" & CStr(PageNo) End If Printer.Print msg ' Output all data of this page Printer.NewPage ' Send new page. NumLines = 0 PageNo = PageNo + 1 msg = Title End If End If Next i End If ' Get here after going thru all lines in the listbox If NumLines > 0 Then ' complete the last page by inserting page number For i = NumLines To MaxLinesPerPage msg = msg & vbCrLf Next i If PageNo > 1 Then msg = msg + vbCrLf & Space$(35) & "Page-" & Str$(PageNo)
15

End If Printer.Print msg ' Output all data of this page End If If HasSome Then Printer.EndDoc ' Initiate the actual Print. Else Beep MsgBox "Nothing to print, try selecting a range of lines first" End If Screen.MousePointer = vbDefault ' Change mousepointer shape back to normal End Sub Ta gi PrintList in nhng Items c selected trong Listbox lstNames nh sau: Private Sub CmdPrint_Click() PrintList lstHexadecimal, True, "*** EVENT LOG IN HEX ***" End Sub Thm Horizontal Scrollbar vo Listbox C l bn thy c hai Listboxes lstASCII v lstHexadecimal u c Horizontal Scrollbar pha di. By default, Listbox khng c Horizontal Scrollbar. Mun to ra n bn phi thm hai cu di y vo mt Basic module: Public Declare Function SendMessage Lib "user32" Alias "SendMessageA" (ByVal hwnd As Long, ByVal wMsg As Long, ByVal wParam As Long, lParam As Any) As Long Global Const LB_SETHORIZONTALEXTENT = &H194 K trong Sub Form_Load gi Function SendMessage qua Application Programming Interface (API) yu cu Listbox cho hin ra Horizontal Scrollbar. Dim VLong As Long ' make a horizontal scrollbar for both Listboxes VLong = SendMessage(lstAscii.hwnd, LB_SETHORIZONTALEXTENT, lstAscii.Width, ByVal 0) VLong = SendMessage(lstHexadecimal.hwnd, LB_SETHORIZONTALEXTENT, lstHexadecimal.Width, ByVal 0) Bn c th download source code ca program Eventlog.zip ny c y . Trong bi ti ta s hc thm cc p dng cn li ca ListBox. Listbox Search trong Text File Ta bit rng ListBox c th cha rt nhiu hng text (con s hng ti a l 65535). Ta quen vi vic hin th content ca mt text file trong mt Listbox. Ta dng ListBox display cc Events (s c) xy ra trong real-time. Gi d, ta ghi li tt c mi Events xy ra trong real-time ca mt h thng an ninh, tc l ta bit ai ra, vo ca no, lc my gi. Cc Events ny va uc log xung mt Text file,
16

va c cho vo mt ListBox lun lun hin th Event mi nht cui ListBox. Khi c mi Events nm trong ListBox, ta c th Search (tm kim) xem mt ngi no i qua nhng ca no ca building bng cch iterate qua tng hng trong ListBox v nhn din mt Text Pattern hng vi Function InStr. Trong bi mu di y, ta nh tn ca mt ngi vo trong TextBox ri click nt Find v sau Find Next highlight nhng Events trong ListBox cho thy nhng lc tn ngi xut hin. Trong khi tm kim mt Text Pattern ta c th cho php c ch Hoa , ln ch Thng bng cch covert mi text ra Uppercase trc khi lm vic vi chng.

Listing ca Sub Find_Click nh sau: Private Sub CmdFind_Click() Dim i, ALine, FText ' Get out if the Listbox is empty If EventList.ListCount = 0 Then MsgBox "There 's no text available" Exit Sub End If ' Check if user has entered the Text Pattern If Trim(txtFind) = "" Then MsgBox "Please enter the Text Pattern to search for" Exit Sub End If ' Clear all selected lines For i = 0 To EventList.ListCount - 1 EventList.Selected(i) = False Next
17

' Convert the Text Pattern to Uppercase FText = UCase(txtFind.Text) ' Iterate through every line in the ListBox For i = 0 To EventList.ListCount - 1 ' Convert this line to Uppercase ALine = UCase(EventList.List(i)) ' If pattern exists in this line then highlight it If InStr(ALine, FText) > 0 Then EventList.Selected(i) = True ' Highlight the line ' Mark Current line as the Starting line for FindNext operation If i < EventList.ListCount - 1 Then CurrentLine = i + 1 ' get out Exit Sub End If Next ' Only get here if Not found MsgBox "Not found!" End Sub Trong bi ny ta c dng mt DriveListBox cho User chn mt Disk drive, mt DirListBox user chn mt Folder/Directory v mt FileListBox hin th tn ca nhng Files trong mt Folder. C ba loi ListBoxes ny lin kt nhau cho ta thy s thay i n nhp mi khi User i t Disk Drive ny qua Disk Drive khc, hay t Folder ny qua Folder khc. Cc hng codes thc hin vic ny rt n gin nh sau: Private Sub Drive1_Change() ' Make Path of Folder same as new Drive Dir1.Path = Drive1.Drive End Sub Private Sub Dir1_Change() ' Make Path of FileList same as new Path of Folder ' The filenames in the Folder will be displayed automatically in FileListBox FileList.Path = Dir1.Path End Sub
Ta c th chn la ch nhng Filenames c mt Extension no (th d nh log) bng cch cho Property Pattern ca FileListBox value "*.log". Mi khi User click ln tn ca mt File, program s load content ca File y vo ListBox EventList bn phi. Sau khi selected mt s hng ri, User c th hoc Print chng ra bng cch Click nt Print , hoc Copy chng vo Clipboard bng cch Click nt Copy. Dng ItemData

Nu Property List ca ListBox c xem nh mt Text Array th ItemData l mt Number Array, v List1.ItemData(i) i cp vi List1.List(i). Tc l trong khi List1.List(i) hin th nh mt trc ca mt tm bn th List1.ItemData(i) c coi nh nm mt sau ca tm bn y. Khi mt List item thay i v
18

tr trong Listbox v c s bin i trong ListBox (th d Items b removed hay c cho thm vo) th ItemData ca List item cng i theo vi n. Ta th xem th d sau. Cho vo mt Sorted Listbox tn ca cc nhn vin trong s. Ngay sau khi tn mt nhn vin c cho vo Listbox th Property NewIndex cha v tr ca item mi c cho vo y trong ListBox. Ta dng gi tr NewIndex assign ItemData vi S nhn vin ID. Khi User clicks ln mt tn trong Listbox, program s hin th c S nhn vin ID ln tn nhn vin. th th d ny, bn c th Paste phn code di y vo phn Declaration ca mt Form c cha mt Listbox v mt Label. Nh set property Sorted ca List1 ra True.

Private Sub Form_Load() ' Fill List1 and ItemData array with ' corresponding items in sorted order. List1.AddItem "John Green" ' Add an employee name ' Use NewIndex to synchronise with Employee ID ' Assign Employee ID to ItemData of the List Item List1.ItemData(List1.NewIndex) = 62310 List1.AddItem "Tran The Tam" List1.ItemData(List1.NewIndex) = 42859 List1.AddItem "Alan Bradshaw" List1.ItemData(List1.NewIndex) = 63732 List1.AddItem "Peter Costello" List1.ItemData(List1.NewIndex) = 34127 End Sub Private Sub List1_Click() ' Fetch the employee number Msg = List1.ItemData(List1.ListIndex) & " " ' Concatenate it with the employee name. Msg = Msg & List1.List(List1.ListIndex) ' Assign string to Label to display Label1.Caption = Msg End Sub Dng ListBox lm Queue
19

Khi i coi ht, ta thng phi ng sp hng mua v. Ci hng gi l Queue. Mc ch ca vic dng Queue l cho s ngi ng cn mt dch v s c phc v ln lt theo th t ai n trc s c gii quyt trc. Nguyn tc ca Queue nh th c gi l First-In-First-Out ( vo trc nht, ra trc nht). Ngc li, nu ai cng mun c phc v trc nht ta s c s no lon, v rt cuc c th chng c ai c gii quyt. Th d ta c mt Form tn frmServer, m trong c mt Listbox tn List1. Nu c nhiu Forms khc trong cng mt chng trnh mun nh frmServer phc v mt chuyn g, chng s Queue bng cch Add mt Item vo cui List1. Trong Item c cha nhng chi tit m frmServer s cn bit phc v. Private Sub CmdAddToQueue_Click() Dim myRequest As String Dim PersonId As String * 5 Dim PersonName As String * 20 ' Assign PersonId to fixed length text PersonId = txtPersonId.Text ' Assign PersonName to fixed length text PersonName = txtPersonName.Text ' Concatenate Id and Name myRequest = PersonId & PersonName ' Queue the request frmServer.List1.AddItem myRequest End Sub Bn frmServer, c mi 3 giy n s Remove Item trn ht ( tc l Index=0) trong List1 v x l Item y. Trong bi ny ta ch Remove Item 0 ri Add n vo List2. Private Sub Timer1_Timer() Dim Item If List1.ListCount > 0 Then ' Look at the item at the head of the queue Item = List1.List(0) ' Process Item - just add it to List2 here List2.AddItem Item ' Remove item from queue List1.RemoveItem 0 End If End Sub

20

CheckBox Listbox Nu bn chn value ca Property Style ca Listbox l CheckBox thay v Standard th mi items trong Listbox s c mt hp vung pha trc User c th chn lc chy program. Hp vung ca item no c checked (nh du) th Item y c Selected. Gi s ta c mt Listbox List1 vi Style Checkbox v c nhiu Items mua trong siu th. Khi chy progarm user chn mt s items ri click nt Process, program s hin th cc item c chn. Listing ca Sub CmdProcess_Click nh sau: Private Sub CmdProcess_Click() Dim Mess As String ' get out if there's nothing in the list If List1.ListCount = 0 Then Exit Sub ' Iterate through every item of the checkBox Listbox For i = 0 To List1.ListCount - 1 ' If item is selected then include it in the shopping list If List1.Selected(i) Then ' Append Item and a Carriage Return-LineFeed Mess = Mess & List1.List(i) & vbCrLf End If Next ' Display shopping list MsgBox Mess, vbInformation, "Selected Shopping Items" End Sub

21

Listbox vi nhiu ct Listbox c mt Property gi l Columns. Bnh thng, Property Columns c gi tr 0. Nhng nu bn cho n bng 3 chng hn, th Listbox s c gng hin th 4 ct trong phm vi chiu ngang ca Listbox. Nu nh th vn khng hin th ht mi Items trong Listbox th s c mt Horizontal Scrollbar hin ra, v khi bn click n qua bn phi Listbox s cho hin th thm cc columns cn li.

Combobox Combobox rt ging nh Listbox. N l tp hp ca mt Textbox nm pha trn User cho vo data v mt Listbox cha cc items m User c th la chn khi m n ra. Combo box cng c nhng methods nh Clear, AddItem v RemoveItem. Tuy nhin, Combobox khng c Property Selected, v khi User chn Item no th Item y c hin th trong Textbox pha trn. Combobox c 3 styles. Drop-down Combo Style l thng dng nht. N cho User nhim hoc chn mt Item t List hoc nh data vo Textbox. Trong hnh di y User nh vo ch Elephant thay v chn t cc Items c sn.

22

Drop-down List bt buc User phi chn mt trong nhng Item nm trong List, ch khng c nh data mi vo Textbox. Ngay c trong lc chy program (at run-time) bn cng khng th Assign mt value vo property Text ca Combobox loi ny. Nhng bn c th lm cho Combobox hin th Item th 3 chng hn bng cch set property ListIndex ca Combo bng 2

23

You might also like