Hướng dẫn sử dụng Dùng List Controls

23 804 0
Hướng dẫn sử dụng Dùng List Controls

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

Hướng dẫn sử dụng Dùng List Controls

Chương Bảy - Dùng List Controls Có hai loại List controls dùng VB6 Ðó Listbox Combobox Cả hai display số hàng để ta lựa chọn Listbox chiếm khung chữ nhật, chiều ngang nhỏ có khơng display đầy đủ hàng, chiều dài không đủ để display tất hàng Listbox tự động cho ta vertical scroll bar biết cịn có nhiều hàng bị che ta xem hàng cách dùng vertical scroll bar Combobox thường thường display hàng, ta chọn display hàng khác Combobox giống tập hợp Textbox nằm phía Listbox nằm phía Listbox có nhiều cơng dụng uyển chuyển Trong chương nầy ta học qua áp dụng sau Listbox: • • • • • • • Display nhiều lựa chọn để User selects cách click hay drag-drop Những cách dùng Property Sorted Cách dùng Multiselect Dùng để display Events Dùng để Search hay process text Cách dùng Itemdata song song với Items List Dùng làm Queue Listbox Display nhiều lựa chọn Ta bắt đầu viết chương trình gồm có Listbox tên lstNames nằm Form Trong lstNames ta đánh vào tên bảy người, lần xuống hàng nhớ đánh Ctrl-Enter, thay Enter, không VB6 tưởng ta đánh xong nên close property List Các tên nầy hàng Listbox ta bắt đầu chạy program Ngoài lstNames ta cho thêm Label với Caption STUDENTS để trang hoàng, Label khác tên lblName Mỗi User click lên hàng tên ta muốn display hàng tên lblName Sau ta cho vào CommandButton tên CmdExit User phương tiện Stop program Ta có chương trì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 vào tên John Smith Listbox, ta thấy tên đuợc display Label lblName Trong thí dụ nầy, Listbox lstNames có hàng ( Items) Con số Items nầy Property ListCount Listbox Các Items Listbox đếm từ đến ListCount-1 Trong trường hợp nầy từ đến Khi User click lên hàng, Listbox generate Event lstNames_Click Lúc ta biết User vừa Click hàng cách hỏi Property ListIndex lstNames, có value từ đến ListCount-1 Lúc program chạy, chưa Click lên Item Listbox ListIndex = -1 Nhũng Items Listbox xem Array String Array nầy gọi List Do đó, ta nói đến Item thứ Listbox lstNames cách viết lstNames.List(0) , tương tợ vậy, Item cuối lstNames.List( lstNames.ListCount-1) Ta nói đến item vừa Clicked hai cách: lstNames.List(lstNames.ListIndex), lstNames.text Save content Listbox Bây để lưu trử content lstNames, ta thêm CommandButton tên CmdSave Ta viết code để User click nút CmdSave program mở Output text file viết items lstNames vào đó: 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 = To lstNames.ListCount - ' 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 Object đặc biệt đại diện cho program chạy Ở ta dùng Property Path để biết lúc program chạy execute module EXE nằm đâu Lý thường thường ta để files liên hệ cần thiết cho program lẩn quẩn folder program hay subfolder, chẳng hạn data, logs, v.v App cịn có số Properties khác hữu dụng PrevInstance, Title, Revision v.v Nếu started program mà thấy App.PrevInstance = True lúc có copy khác program chạy Nếu cần ta End program nầy để tránh chạy copies program lúc App.Title App.Revision cho ta tin tức Title Revision program chạy Ðể viết Text file ta cần phải Open mode Output tuyên bố từ trở dùng số (FileNumber) để đại diện File thay dùng FileName Ðể tránh dùng FileNumber hữu, tốt ta hỏi xin Operating System cung cấp cho số chưa dùng cách gọi Function FreeFile Con số FileNumber nầy đuợc gọi FileHandle (Handle tay cầm) Sau ta Close FileNumber số nầy trở nên FREE Operating System dùng lại Do bạn phải tránh gọi FreeFile liên tiếp hai lần, OS cho bạn số Tức là, sau gọi FreeFile phải dùng cách Open File gọi FreeFile lần kế để có số khác Ðể ý cách dùng chữ Input, Output cho files relative (tương đối) với vị trí program (nó nằm memory computer) Do từ memory viết hard disk nói Output Ngược lại đọc từ Text file nằm hard disk vào memory cho program ta gọi Input Load Text file vào Listbox Trong nầy, thay đánh Items Listbox vào Property List lstNames ta populate (làm đầy) lstNames cách đọc Items từ Text file Ta thử thêm CommandButton tên CmdLoad Ta viết code để User click nút CmdLoad program mở Input text file đọc hàng để bỏ vào 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ừ Text file ta cần phải Open mode Input Trước populate lstNames ta cần phải delete tất items có sẵn bên Ðể thực việc ta dùng method Clear Listbox Sau ta dùng method AddItem thêm hàng vào Listbox By default, ta khơng nói nhét vào chỗ hàng AddItem nhét Item vào chót Listbox Nếu muốn nhét hàng vào trước item thứ (ListIndex = 4), ta viết: lstNames.AddItem newItemString, ' newItemString contains "Ross Close", for example ' To insert a new Item at the beginning of the Listbox, write: lstNames.AddItem newItemString, Nhớ lần bạn Add Item vào Listbox ListCount Listbox increment by Muốn delete item từ Listbox ta dùng method RemoveItem, thí dụ muốn delete item thứ ba (ListIndex=2) lstNames, ta viết: lstNames.RemoveItem Mỗi lần bạn RemoveItem từ Listbox the ListCount Listbox decrement by Do bạn dùng Test dựa vào ListCount ListBox để nhảy khỏi Loop phải coi chừng tránh làm cho value ListCount thay đổi Loop AddItem hay RemoveItem Ta đọc hàng Text file cách dùng Line Input #FileNumber Khi đọc đến cuối File, system dẽ cho ta value EOF(FileNumber) = True Ta dùng value program nhảy khỏi While Loop Câu Do While NOT EOF(FileNumber) có nghĩa Trong chưa đến End-Of-File Text File đại diện FileNumber đọc từ hàng bỏ vào Listbox Giống "Trong chưa trả hết nợ nhà vợ phải tiếp tục rể" Drag-Drop Ta học qua Click Event Listbox Bây để dùng Drag-Drop cho Listbox bạn đặt Labels lên Form Cái thứ tên có Caption Room A Hãy gọi Label thứ hai lblRoom cho Property BorderStyle Fixed Single Kế đến select hai Labels (Click a Label then hold down key Ctrl while clicking the second Label) click copy paste lên Form VB6 cho bạn Array hai lblRoom labels Ðể cho lstNames DragIcon, bạn click lstNames, click Property DragIcon để pop-up dialog cho bạn chọn dragdrop icon từ folder C:\Program Files\Microsoft Visual Studio\Common\Graphics\Icons\Dragdrop, chẳng hạn DRAG2PG.ICO: Ta dùng Event MouseDown lstNames để pop-up DragIcon hình trang giấy cho User Drag qua bên phải bỏ xuống lên hai lblRoom Khi DragIcon rơi lên lblRoom, lblRoom generate Event DragDrop Ta dùng Event DragDrop nầy để assign property Text Source (tức lstNames, control từ phát xuất Drag action) vào Property Caption lblRoom Lưu ý ta dùng tên cho hai lblRoom nên cần viết code 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 Kết sau Drag hai tên từ Listbox qua Labels sau: Dùng Property Sorted Trong thí dụ ta định vị trí Item ta nhét vào Listbox Ðôi ta muốn Items Listbox tự động theo thứ tự Alphabet Bạn set Property Sorted = True để thực chuyện nầy Có giới hạn bạn phải cho Property Sorted value (True hay False) lúc design, chạy program bạn làm cho Property Sorted Listbox thay đổi Giả dụ ta muốn sort Items Listbox cần Vậy ta làm sao? Giải pháp đơn giản Bạn tạo Listbox tên lstTemp chẳng hạn Cho Property Visible= False (để khơng thấy nó) Property Sorted=True Khi cần sort lstNames chẳng hạn, ta copy content lstNames bỏ vào lstTemp, đoạn Clear lstNames copy content (đã sorted) lstTemp trở lại lstNames Lưu ý ta AddItem vào Listbox với Property Sorted=True, xác định nhét Item vào trước hàng nào, vị trí Items Listbox định sort Items Ta cho thêm vào Form CommandButton tên CmdSort viết code cho Event Click sau: Private Sub CmdSort_Click() Dim i lstTemp.Clear ' Clear temporary Listbox ' Iterate though every item of lstNames For i = To lstNames.ListCount - ' Add the lstNames item to lstTemp lstTemp.AddItem lstNames.List(i) Next lstNames.Clear ' Clear lstNames ' Iterate though every item of lstTemp For i = To lstTemp.ListCount - ' Add the lstTemp item to lstNames lstNames.AddItem lstTemp.List(i) Next lstTemp.Clear ' Tidy up - clear temporary Listbox End Sub Nhân tiện, ta muốn có option để sort tên theo FirstName hay Surname Việc nầy rắc rối chút, nguyên tắc dùng sorted Listbox vơ hình tên lstTemp Bạn đặt lên phía lstName hai cál Labels tên lblFirstName lblSurName cho chúng Caption "FirstName" "SurName" Từ ta Load file "MyList.txt" vào lstNames cách Click button CmdLoad không Edit Property List lstNames để enter Items lúc design Ngoài ta dùng dấu phẩy (,) để tách FirstName khỏi SurName tên chứa file MyList.txt Content file MyList.txt trở thành sau: Peter,Jones Kevin,White Sue,Rose John,Smith Trevor,Kennedy Alan,Wright Ron,Bruno Ta sửa code Sub CmdLoad_Click lại để nhét tên vào lstNames, FirstName SurName thứ chiếm 10 characters Ðể chữ Items lstNames hàng ngắn ta đổi Font lstNames Courier New Courier New loại Font mà chiều ngang chữ m chữ i, hầu hết Fonts khác Arial, Times Roman v.v Proportional Spacing, có nghĩa chữ m rộng chữ i Listing Sub CmdLoad_Click trở thà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) 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 nằm bên trái Item nên sort theo FirstName giống sort Item Việc ta làm Sub CmdSort_Click rồi, User click Label lblFirstName ta cần gọi CmdSort_Click sau: Private Sub lblFirstName_Click() CmdSort_Click End Sub Ðể sort theo SurName ta cần phải tạm thời để SurName qua bên trái Item trước bỏ vào lstTemp Ta thực chuyện nầy cách hoán chuyển vị trí FirstName SurName Item trước bỏ vào lstTemp Sau đó, copy Items từ lstTemp để bỏ vơ lại lstNames ta lại nhớ hốn chuyển FirstName SurName để chúng nằm lại vị trí Tức là, mánh ta muốn biết Item phải nằm đâu lstNames, dĩ nhiên display Item có FisrtName bên trái Code để sort tên theo SurName giống CmdSort_Add thêm thắt chút 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 = To lstNames.ListCount - 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 = To lstTemp.ListCount - 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 End Sub Các Items lstNames sorted theo SurName sau: Nhân tiện ta sửa Sub CmdSave_Click lại chút để Save Items theo sorted order cần: 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 = To lstNames.ListCount - 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 tới ta học thêm áp dụng khác ListBox Listbox Cách dùng MultiSelect Cho đến User click vào Listbox để chọn Item Khi Item chọn hàng trở nên highlighted với background màu xanh đậm Nếu kế ta click hàng khác hàng cũ display trở lại bình thường hàng đuợc selected trở nên highlighted Listbox cho ta select nhiều Items lúc cách set Property MultiSelect = Extended Ðối với MultiSelected Listbox, ta chọn nhóm Items liên tục cách click Item đầu nhấn nút Shift click Item cuối Ta tiếp tục Select/Deselect thêm cách ấn nút Ctrl click Items Nếu ta click Item chưa selected trở nên selected (highlighted màu xanh), ta click Item selected trở nên deselected (khơng cịn màu xanh nữa) Thí dụ program bạn click "Peter Jones", kế ấn nút Shift click "Sue Rose", kế bng nút Shift để ấn nút Ctrl click "Kevin White", bạn có selected Items hình đây: Ngồi bạn MultiSelect nhiều Items Listbox cách dùng mouse để drag, tức bạn click lên Item đầu tiếp tục đè mousebutton kéo mousepointer đến Item cuối buông mousebutton Cái Bug ác ôn Bây giả sử ta muốn delete tất Items vừa selected (highlighted) Bạn đặt CommandButton tên CmdDeleteSelectedItems vào Form Ta dùng Event Click Button nầy để delete selected Items Một selected Item lstNames có property Selected True Tức Item thứ ba (ListIndex=2) selected ta có lstNames.Selected(2) = True Ta có ý định iterate through Items lstNames, để xem Item selected delete cách dùng method RemoveItem Ta viết code cho Sub CmdDeleteSelectedItems_Click() sau: Private Sub CmdDeleteSelectedItems_Click() Dim i 10 For i = To lstNames.ListCount - If lstNames.Selected(i) = True Then lstNames.RemoveItem i End If Next End Sub Bạn chạy chương trình, click Load để populate lstNames với tên đọc từ text file, MultiSelect tên hình phía Kế click button DeleteSelectedItems Program té (crash) có sau: Nếu bạn click nút Debug, program ngừng dòng code gặp error highlight với background màu vàng Ðể mousepointer lên chữ i lstNames.Selected(i), VB6 popup message nho nhỏ i = Bạn để ý thấy hình lúc nầy lstNames cịn có Items (Ron, Trevor, John Alan), Items bị removed Bạn có biết program crashed khơng? Ðó program refer đến property Selected Item thứ năm ( ArrayIndex i = 4) lstNames lstNames cịn có Items Vì program crashed với message "Runtime error '381': Invalid property array index" Thủ phạm Bug ác ôn nầy statement For i = To lstNames.ListCount - VB6 tính value lstNames.ListCount -1 lần lúc khởi For Loop mà (tức lstNames.ListCount -1 = 6), khơng lưu ý ListCount giảm value lần Item bị Removed Ngoài ta thấy tên "Trevor Kennedy" không bị removed, tức bị lọt sổ ta dùng For Loop theo cách nầy Lý sau ta Remove "Peter Jones" (Item thứ hai), "Trevor Kennedy" bị đẩy lên trở thành Item thứ hai Kế ta increment value i thành process Item thứ ba, tức "Sue Rose", nên "Trevor Kennedy" không processed 11 Sub CmdDeleteSelectedItems_Click cần phải viết lại để dùng While Loop, thay For Loop Trong While Loop, lstNames.ListCount - evaluated (tính) để test iteration Khi ta Remove Item ta khơng increment i, Item removed Item đẩy lên Listing sau: Private Sub CmdDeleteSelectedItems_Click() Dim i i = ' Initialise value of i to start from first Item ' Note that lstNames.ListCount is evaluated freshly at each iteration Do While i = 1000 Then ' Remove the first Item, i.e the oldest item lstHexadecimal.RemoveItem End If ' Highlight the lattest item in the Listbox 13 lstHexadecimal.ListIndex = lstHexadecimal.ListCount - ' 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, End Sub In content Listbox Dưới áp dụng Listbox MutiSelect để in Listbox hay hàng selected Sub PrintList nhận: • • • Listbox mà ta muốn in Boolean value mà True in Listbox Title 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 characters Title = vbLf & vbLf & Title + vbCrLf & vbLf NumLines = ' Init number of lines on this page PageNo = ' 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 > Then ' get here if the listbox is not empty For i = To theList.ListCount - ' 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 + ' 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 > Then ' Add extra blank lines to make up a page before inserting page number 14 For j = NumLines - 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 = ' reset Number of lines, counting this current line PageNo = PageNo + ' 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 > 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 = PageNo = PageNo + msg = Title End If End If Next i End If ' Get here after going thru all lines in the listbox If NumLines > Then ' complete the last page by inserting page number For i = NumLines To MaxLinesPerPage msg = msg & vbCrLf Next i If PageNo > 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 gọi PrintList để in Items selected Listbox lstNames sau: Private Sub CmdPrint_Click() PrintList lstHexadecimal, True, "*** EVENT LOG IN HEX ***" End Sub Thêm Horizontal Scrollbar vào Listbox Có lẽ bạn để ý thấy hai Listboxes lstASCII lstHexadecimal có Horizontal Scrollbar phía By default, Listbox khơng có Horizontal Scrollbar Muốn tạo bạn phải thêm hai câu vào 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ế Sub Form_Load gọi Function SendMessage qua Application Programming Interface (API) để yêu cầu Listbox cho 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) Bạn download source code program Eventlog.zip nầy để có đầy đủ Trong tới ta học thêm áp dụng lại ListBox Listbox Search Text File Ta biết ListBox chứa nhiều hàng text (con số hàng tối đa 65535) Ta quen với việc hiển thị content text file Listbox Ta dùng ListBox để display Events (sự cố) xãy real-time Giả dụ, ta ghi lại tất Events xãy real-time hệ thống an ninh, tức ta biết ra, vào cửa nào, lúc Các Events nầy vừa đuợc log xuống Text file, 16 vừa cho vào ListBox để luôn hiển thị Event cuối ListBox Khi có Events nằm ListBox, ta Search (tìm kiếm) xem người qua cửa building cách iterate qua hàng ListBox nhận diện Text Pattern hàng với Function InStr Trong mẫu đây, ta đánh tên người vào TextBox click nút Find sau Find Next để highlight Events ListBox cho thấy lúc tên người xuất Trong tìm kiếm Text Pattern ta cho phép chữ Hoa , lẫn chữ Thường cách covert text Uppercase trước làm việc với chúng Listing Sub Find_Click sau: Private Sub CmdFind_Click() Dim i, ALine, FText ' Get out if the Listbox is empty If EventList.ListCount = 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 = To EventList.ListCount - 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 = To EventList.ListCount - ' Convert this line to Uppercase ALine = UCase(EventList.List(i)) ' If pattern exists in this line then highlight it If InStr(ALine, FText) > Then EventList.Selected(i) = True ' Highlight the line ' Mark Current line as the Starting line for FindNext operation If i < EventList.ListCount - Then CurrentLine = i + ' get out Exit Sub End If Next ' Only get here if Not found MsgBox "Not found!" End Sub Trong nầy ta có dùng DriveListBox User chọn Disk drive, DirListBox để user chọn Folder/Directory FileListBox để hiển thị tên Files Folder Cả ba loại ListBoxes nầy liên kết ta thấy thay đổi ăn nhịp User đổi từ Disk Drive nầy qua Disk Drive khác, hay từ Folder nầy qua Folder khác Các hàng codes thực việc nầy đơn giản 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 chọn lựa Filenames có Extension (thí dụ log) cách cho Property Pattern FileListBox value "*.log" Mỗi User click lên tên File, program load content File vào ListBox EventList bên phải Sau selected số hàng rồi, User Print chúng cách Click nút Print, Copy chúng vào Clipboard cách Click nút Copy Dùng ItemData Nếu Property List ListBox xem Text Array ItemData Number Array, List1.ItemData(i) cặp với List1.List(i) Tức List1.List(i) hiển thị mặt trước List1.ItemData(i) coi nằm mặt sau Khi List item thay đổi vị 18 trí Listbox có biến đổi ListBox (thí dụ Items bị removed hay cho thêm vào) ItemData List item theo với Ta thử xem thí dụ sau Cho vào Sorted Listbox tên nhân viên sở Ngay sau tên nhân viên cho vào Listbox Property NewIndex chứa vị trí item cho vào ListBox Ta dùng giá trị NewIndex để assign ItemData với Số nhân viên ID Khi User clicks lên tên Listbox, program hiển thị Số nhân viên ID lẫn tên nhân viên Ðể thử thí dụ nầy, bạn Paste phần code vào phần Declaration Form có chứa Listbox Label Nhớ set property Sorted List1 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 Dùng ListBox làm Queue 19 Khi coi hát, ta thường phải đứng hàng để mua vé Cái hàng gọi Queue Mục đích việc dùng Queue số người đông cần dịch vụ phục vụ theo thứ tự đến trước giải trước Nguyên tắc Queue gọi First-In-First-Out ( vào trước nhất, trước nhất) Ngược lại, muốn phục vụ trước ta có náo loạn, rốt chẳng có giải Thí dụ ta có Form tên frmServer, mà có Listbox tên List1 Nếu có nhiều Forms khác chương trình muốn nhờ frmServer phục vụ chuyện gì, chúng Queue cách Add Item vào cuối List1 Trong Item có chứa chi tiết mà frmServer cần biết để phục vụ Private Sub CmdAddToQueue_Click() Dim myRequest As String Dim PersonId As String * 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 Bên frmServer, giây Remove Item hết ( tức Index=0) List1 xử lý Item Trong nầy ta Remove Item Add vào List2 Private Sub Timer1_Timer() Dim Item If List1.ListCount > 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 End If End Sub 20 CheckBox Listbox Nếu bạn chọn value Property Style Listbox CheckBox thay Standard items Listbox có hộp vng phía trước để User chọn lúc chạy program Hộp vng item checked (đánh dấu) Item Selected Giả sử ta có Listbox List1 với Style Checkbox có nhiều Items để mua siêu thị Khi chạy progarm user chọn số items click nút Process, program hiển thị item chọn Listing Sub CmdProcess_Click sau: Private Sub CmdProcess_Click() Dim Mess As String ' get out if there's nothing in the list If List1.ListCount = Then Exit Sub ' Iterate through every item of the checkBox Listbox For i = To List1.ListCount - ' 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 với nhiều cột Listbox có Property gọi Columns Bình thường, Property Columns có giá trị Nhưng bạn cho chẳng hạn, Listbox cố gắng hiển thị cột phạm vi chiều ngang Listbox Nếu không đủ hiển thị hết Items Listbox có Horizontal Scrollbar ra, bạn click qua bên phải Listbox cho hiển thị thêm columns lại Combobox Combobox giống Listbox Nó tập hợp Textbox nằm phía để User cho vào data Listbox chứa items mà User lựa chọn mở Combo box có methods Clear, AddItem RemoveItem Tuy nhiên, Combobox khơng có Property Selected, User chọn Item Item hiển thị Textbox phía Combobox có styles Drop-down Combo Style thơng dụng Nó cho User nhiệm ý chọn Item từ List đánh data vào Textbox Trong hình User đánh vào chữ Elephant thay chọn từ Items có sẵn 22 Drop-down List bắt buộc User phải chọn Item nằm List, không đánh data vào Textbox Ngay lúc chạy program (at run-time) bạn Assign value vào property Text Combobox loại nầy Nhưng bạn làm cho Combobox hiển thị Item thứ chẳng hạn cách set property ListIndex Combo 23 ... 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... cách Click nút Copy Dùng ItemData Nếu Property List ListBox xem Text Array ItemData Number Array, List1 .ItemData(i) cặp với List1 .List( i) Tức List1 .List( i) hiển thị mặt trước List1 .ItemData(i)... content Listbox Dưới áp dụng Listbox MutiSelect để in Listbox hay hàng selected Sub PrintList nhận: • • • Listbox mà ta muốn in Boolean value mà True in Listbox Title Printout Sub PrintList(theList

Ngày đăng: 28/08/2012, 15:46

Hình ảnh liên quan

Ta sẽ dùng Event MouseDown của lstNames để pop-up DragIcon hình 2 trang giấy cho User Drag nó qua bên phải rồi bỏ xuống lên một trong hai lblRoom - Hướng dẫn sử dụng Dùng List Controls

a.

sẽ dùng Event MouseDown của lstNames để pop-up DragIcon hình 2 trang giấy cho User Drag nó qua bên phải rồi bỏ xuống lên một trong hai lblRoom Xem tại trang 5 của tài liệu.
Bạn để ý thấy trong hình lúc nầy lstNames chỉ còn có 4 Items (Ron, Trevor, John và Alan), vì các Items kia đã bị removed. - Hướng dẫn sử dụng Dùng List Controls

n.

để ý thấy trong hình lúc nầy lstNames chỉ còn có 4 Items (Ron, Trevor, John và Alan), vì các Items kia đã bị removed Xem tại trang 11 của tài liệu.
Hình dưới đây cho thấy Form đang display trong ASCII mode. - Hướng dẫn sử dụng Dùng List Controls

Hình d.

ưới đây cho thấy Form đang display trong ASCII mode Xem tại trang 12 của tài liệu.

Từ khóa liên quan

Tài liệu cùng người dùng

Tài liệu liên quan