Optimize code In Textchange Richtextbox

ryoka012

Active member
Joined
Oct 13, 2011
Messages
32
Programming Experience
Beginner
Hi experts.

Can any one help on how can i optimize my code below.
IT check the string you type and change the color if the string does not find it.
My problem is When the string are simple enough it work fine but when the string are long it flicker and it hang.

This is my long array of string
VB.NET:
Dim ArrayValue() As String = {"A.I.D.", "AA", "AAR", "ABAFT", "ABANDON", "ABATEMENT", "ABOARD", "ACCEPTANCE", "ACCESSORIAL CHARGES", "ACQUIESCENCE", "ACQUITTANCE", "ACT OF GOD", "AD VALOREM", "ADMINISTRATIVE LAW JUDGE", "ADMIRALTY (ADM.)", "ADVANCE", "ADVANCED CHARGE", "ADVANCED NOTICE OFARRIVAL (ANOA)", "ADVENTURE", "ADVICE OF SHIPMENT", "ADVISING BANK", "AFFREIGHTMENT CONTRACT OF", "AFRAMAX TANKER", "AFT", "AGENCY TARIFF", "AGENT (AGT.)", "AGGREGATE SHIPMENT", "AGREED VALUATION", "AGREED WEIGHT", "AIR WAYBILL", "AIR WAYBILL (AWB)", "ALL IN", "ALLISION", "ALONGSIDE", "ALTERNATIVE RATES", "AMBIENT TEMPERATURE", "ANTI DUMPING DUTY", "ANY QUANTITY (A.Q.)", "APPARENT GOOD ORDER", "APPRAISEMENT", "APPRAISERS STORES", "ARBITRARY", "ARRIVAL NOTICE", "ASSESSMENT OF DUTIES AND TAXES", "ASSIGNMENT", "ASTERN", "ATDNSHINC", "ATHWART SHIPS", "AUTOMATED COMMERCIAL ENVIRONMENT (ACE)", "AUTOMATED IDENTIFICATIONSYSTEM (AIS)", "AVOIRDUPOIS POUND", "B/L", "ABSORPTION", "AMENDED B/L", "AWWL", "B/L TERMS &AMP,CONDITIONS", "B/LS STATUS", "BAF", "BALLOON FREIGHT", "BANK GUARANTEE", "BARRATRY", "BARREL (BBL)", "BASE RATE", "BB", "BCO", "BEAM", "BELT LINE", "BENEFICIARY", "BERTH TERMS", "BEYOND", "BILATERAL", "BILL OF LADING", "BILL OF LADING (B/L)", "BLOCKINGOR BRACING", "BLS", "BOARD", "BOARDFEET", "BOAT", "BOBTAIL", "BOGIE", "BOLSTER", "BOND PORT", "BONDED FREIGHT", "BONDED WAREHOUSE", "BOOKING", "BOOKING NUMBER", "BOTTOM AIR DELIVERY", "BOTTOM SIDE RAILS", "BOW", "BOXCAR", "BREAK BULK", "BRIDGE POINT", "BRIDGE PORT", "BROKEN STOWAGE", "BROKER", "BROKERAGE", "BULK CARGO", "BULK FREIGHT CONTAINER", "BULKHEAD", "BULL RINGS", "BUNKER CHARGE", "BUNKERS", "BUREAU VERITAS", "C TPAT (CUSTOMS TRADE PARTNERSHIP AGAINS", "C&AMP,F TERMS OF SALE OR INCOTERM", "CABOTAGE", "CAF", "CANCELLED B/L", "CAPESIZE VESSEL", "CAPTAINS PROTEST", "CAR POOLING", "CAR SEAL", "CARFLOAT", "CARGO", "CARGO MANIFEST", "CARGO NOS", "CARGO PREFERENCE", "CARGO TONNAGE", "CARLOAD RATE", "CARNET", "CARRIER", "CARRIERS CERTIFICATE", "CARTAGE", "CARTMENT", "CASH AGAINST DOCUMENTS (CAD)", "CASH IN ADVANCE (CIA)", "CASH WITH ORDER (CWO)", "CBM (CM)", "CCC MARK", "CE", "CE MARK", "CELL", "CENTRE OF GRAVITY", "CERTIFICATE OF INSPECTION", "CERTIFICATE OF ORIGIN", "CFS", "CHARTER PARTY", "CHASSIS", "CHOCK", "CI", "CIF (NAMED PORT)", "CIF&AMP,C", "CIF&AMP,E", "CIFCI", "CIFI&AMP,E", "CKD", "CL", "CLAIM", "CLASSIFICATION", "CLASSIFICATION RATING", "CLASSIFICATION SOCIETY", "CLASSIFICATION YARD", "CLEAN B/L", "CLEAN BILL OF LADING", "CLEANING IN TRANSIT", "CLEARANCE LIMITS", "CLEAT", "CLIP ON", "CM", "COASTWISE", "COD", "COFC", "COLLECTING", "COLLECTION", "COMBINED B/L", "COMMERCIAL INVOICE", "COMMERCIAL INVOICE (CI)", "COMMERCIAL TRANSPORT VESSEL", "COMMODITY", "COMMODITY RATE", "COMMON CARRIER", "COMMON LAW", "COMPANY SECURITY OFFICER", "COMPULSORY SHIP", "CONCEALED DAMAGE", "CONFERENCE", "CONFIRMED LETTER OF CREDIT", "CONFIRMING BANK", "CONNECTING CARRIER", "CONNECTING CARRIER AGREEMENT", "CONSIGNEE", "CONSIGNEE MARK", "CONSIGNMENT", "CONSIGNOR", "CONSOLIDATED B/L", "CONSOLIDATION", "CONSOLIDATOR", "CONSUL", "CONSULAR DECLARATION", "CONSULAR INVOICE", "CONSULAR VISA", "CONSUMPTION ENTRY (CE)", "CONTAINER", "CONTAINER BOOKING", "CONTAINER LOAD", "CONTAINER MANIFEST", "CONTAINER POOL", "CONTAINER TERMINAL", "CONTAINER YARD (CY)", "CONTAINERISABLE CARGO", "CONTAINERIZATION", "CONTRABAND", "CONTRACT", "CONTRACT CARRIER", "CONTROLLED ATMOSPHERE", "CORNER POSTS", "CORRECTED B/L", "CORRESPONDENT BANK", "COST AND FREIGHT (C&AMP,F)", "COST INSURANCE AND FREIGHT (CIF)", "COUNTERVAILING DUTY", "COUNTRY OF ORIGIN OF GOODS", "CROSS MEMBER", "CU", "CUBE OUT", "CUBIC FOOT", "CUSTOMHOUSE", "CUSTOMHOUSE BROKER", "CUSTOMS", "CUSTOMS AND BORDER PROTECTION (CBP)", "CUSTOMS BONDED WAREHOUSE", "CUSTOMS DECLARATION", "CUSTOMS ENTRY", "CUSTOMS INVOICE", "CUSTOMS OF THE PORT (COP)", "CUSTOMS SELF ASSESSMENT (CSA)", "CUSTOMS TRADE PARTNERSHIP AGAINST TERROR", "CUSTOMS TRADE PARTNERSHIPAGAINST TERRORI", "CUT OFF TIME", "CWT", "CY", "D&AMP,H", "D.B.A.", "D.O.T.", "DDC", "DEADHEAD", "DEADWEIGHTCARGO", "DEADWEIGHTTONNAGE (DWT)", "DECONSOLIDATIONPOINT", "DEFICITWEIGHT", "DELIVERYINSTRUCTIONS", "DEMDES", "DEMURRAGE", "DENSITY", "DEPARTMENT OF HOMELANDSECURITY (DHS)", "DEPOTCONTAINER", "DESPATCH", "DESTINATION", "DESTINATION CONTROL STATEMENTS", "DETENTION", "DETNORSKE VERITAS", "DEVANNING", "DF CAR", "DIFFERENTIAL", "DISCREPANCYLETTER OF CREDIT", "DISPATCH", "DISPLACEMENT", "DIVERSION", "DIVISION", "DOCK", "DOCKAGE", "DOCKET", "DOCKRECEIPT", "DOCUMENTSAGAINST ACCEPTANCE (D/A)", "DOCUMENTSAGAINST PAYMENT (D/P)", "DOLLY", "DOOR TO DOOR", "DRAFT", "DRAFT DATE", "DRAFTBANK", "DRAFTCLEAN", "DRAFTDISCOUNTED", "DRAFTSIGHT", "DRAFTTIME", "DRAWBACK", "DRAWEE", "DRAYAGE", "DRFS", "DRY BULKCONTAINER", "DRYCARGO", "DSU", "DUMPING", "DUNNAGE", "DUTIABLEVALUE", "DWT", "E.W.I.B.", "EDGE PROTECTOR", "EDI", "EDIFACT", "ELECTRONIC DATA INTERCHANGE FOR ADMINIST", "ELECTRONIC DATAINTERCHANGE (EDI)", "ELECTRONIC MANIFEST (EMANIFEST)", "ELEVATING", "EMBARGO", "EMINENT DOMAIN", "EMPTY REPO", "ENDORSEMENT", "ENTRY", "EQUALIZATION", "EQUIPMENT INTERCHANGERECEIPT (EIR)", "ETA C D R S", "ETHYLENE", "EUROPEAN ECONOMIC COMMUNITY(EEC)", "EX", "EX DEC", "EXCEPTION", "EXIM BANK", "EXPIRY DATE", "EXPORT", "EXPORT DECLARATION", "EXPORT LICENSE", "EXPORT PERMIT", "EXPORT QUOTAS", "EXPORT RATE", "EXPRESS B/L", "EXWORKS", "FOOD AND DRUG ADMINISTRATION (FDA)", "F.D.A.", "FACTOR", "FAK", "FALSE BILLING", "FAS", "FCL", "FD", "FEEDER SERVICE", "FEEDER VESSEL", "FEU", "FIFTH WHEEL", "FIO", "FIRKIN", "FIXED COSTS", "FLAT CAR", "FLAT RACK/FLAT BEDCONTAINER", "FMC (F.M.C.)", "FOB", "FOB FREIGHT ALLOWED", "FOB FREIGHT PREPAID", "FOB NAMED POINT OFEXPORTATION", "FOB VESSEL", "FOR", "FORCE MAJEURE", "FORE AND AFT", "FOREIGN SALES CORPORATION", "FOREIGN TRADE ZONE", "FOREIGN TRADE ZONE (FTZ)", "FORK LIFT", "FOUL BILL OF LADING", "FOUR WAY PALLET", "FPPI", "FREE ALONGSIDE (FAS)", "FREE ASTRAY", "FREE CARRIER (FCA)", "FREE IN AND OUT (FIO)", "FREE OF PARTICULARAVERAGE (FPA)", "FREE ON BOARD (FOB U.S.DOMESTIC USE)", "FREE ON BOARD (FOB)", "FREE OUT (FO)", "FREE PORT", "FREE SALE CERTIFICATE", "FREE TIME", "FREE TRADE ZONE", "FREIGHT", "FREIGHT B/L", "FREIGHT BILL", "FREIGHT FORWARDER", "FREIGHTERS", "FULL AND DOWN", "FULL SHIPLOAD LOT", "GATEWAY", "GATT", "GBL", "GDSM", "GENERALORDER (G.O.)", "GENERATORSET (GEN SET)", "GLOBALMARITIME INTELLIGENCE INTEGRATION", "GO DOWN", "GOOSENECK", "GRI", "GROSSTONNAGE (GT)", "GROSSWEIGHT", "GROUPAGE", "GVW", "HARMONIZED SYSTEM CODE (HS CODE)", "HAGUERULES THE", "HANDYMAXVESSEL", "HARBOUR/ HARBOUR", "HARBOURMASTER", "HARMONIZEDSYSTEM OF CODES (HS)", "HATCH", "HAZ MAT", "HEAVY LIFTCHARGE", "HIGH DENSITYCOMPRESSION", "HITCHMENT", "HITCHMENTB/L", "HOPPERBARGE", "HOUSE TOHOUSE", "HOUSE TOPIER", "HOUSEB/L", "I.M.C.O.", "I.M.D.G. CODE", "I.S.O.", "I.T.", "I/A", "ICC", "IE", "IMMEDIATE EXPORTATION", "IMPORT LICENSE", "IMPORTER OF RECORD (IOR)", "IN BOND", "IN GATE", "IN TRANSIT", "IN TRANSIT ENTRY (I.T.)", "INCENTIVE RATE", "JACOBSLADDER", "JETTISON", "JIT", "JOINTRATE", "KILOGRAM", "KING PIN", "KNOCKEDDOWN (KD)", "KNOT", "KNOWNLOSS", "L/C", "LANDBRIDGE", "LANDEDCOST", "LANDINGCERTIFICATE", "LANDINGGEAR", "LANEMETER", "LASH", "LAYCAN", "LCL", "LESSTHAN TRUCKLOAD", "LETTEROF INDEMNITY", "LICENSES", "LIEN", "LIGHTENING", "LIGHTER", "LIGHTERAGE", "LINE HAUL", "LINER", "LIST", "LNG(LIQUEFIED NATURAL GAS)", "LNGC (LNG CARRIER)", "LOADLINE", "LOCALCARGO", "LONG TON", "LONGSHOREMAN", "LOOSE", "LOW BOY", "MEMORANDUM OF UNDERSTANDING (MOU)", "MALPRACTICE", "MANDAMU", "MANIFEST", "MARINEINSURANCE", "MARITIME", "MARITIMEDOMAIN", "MARITIMEDOMAIN AWARENESS (MDA)", "MARITIMESECURITY AND SAFETY INFORMATION", "MARKING", "MARLINESPIKE", "MARVIEW", "MATES RECEIPT", "MBM", "MCFS", "MEASUREMENTCARGO", "MEASUREMENTTON", "MECHANICALLYVENTILATED CONTAINER", "MEMORANDUMBILL OF LADING", "MEMORANDUMFREIGHT BILL", "METER", "METRICTON", "MICROBRIDGE", "MILE", "MINILANDBRIDGE", "MINIMUM CHARGE", "MINIMUMBILL OF LADING", "MIXEDCONTAINER LOAD", "MLB", "MODIFIEDATMOSPHERE", "MSA", "MTSA", "MULTIMODAL", "MULTITANKCONTAINER", "NORTH AMERICAN FREE TRADE AGREEMENT (NAF", "N.C.I.T.D.", "N.M.F.C.", "N.P.C.F.B.", "NAUTICALMILE", "NAVALCOOPERATION AND GUIDANCE FOR SHIPPI", "NCB", "NEC", "NEGOTIABLEINSTRUMENTS", "NES", "NESTED", "NET TAREWEIGHT", "NETTONNAGE (NT)", "NETWEIGHT", "NEUTRALBODY", "NIPPON KAIJI KYOKAI (NK)", "NO SHOW", "NOI", "NOIBN", "NOMENCLATUREOF THE CUSTOMS COOPERATION C", "NON DUMPINGCERTIFICATE", "NON VESSELOPERATING COMMON CARRIER (NVOC", "NOR", "NOS", "NOSE", "NRT NETREGISTER TONS SEE NET TONNAGE", "OCEANBILL OF LADING (OCEAN B/L)", "DS", "O.E.C.D.", "O.P.I.C.", "ON BOARD", "ON DECK", "OPEN SEA", "OPEN TOPCONTAINER", "OPENACCOUNT", "OPENINSURANCE POLICY", "OPERATINGRATIO", "OPTIMUMCUBE", "ORDER NOTIFY(O/N)", "ORFS", "ORIGIN", "ORIGINALBILL OF LADING (OBL)", "P&AMP,", "PACKING LIST", "PADAG", "PAIRED PORTS", "PALLET", "PANAMAX TANKER", "PANAMAX VESSEL", "PAPER RAM", "PAPER RATE", "PARCEL RECEIPT", "PARTIAL SHIPMENTS", "PER DIEM", "PERILS OF THE SEA", "PHYTOSANITARY INSPECTION CERTIFICATE", "PICKUP", "QUAY", "QUOTA", "QUOTATION", "RAG TOP", "RAILDIVISION", "RAILGROUNDING", "RAMP", "RAMP TO DOOR", "RAMP TO RAMP", "RATEBASIS", "RECONSIGNMENT", "RECOURSE", "REDLABEL", "REEFER", "RELATEDPOINTS", "RELAY", "REMITTANCE", "RESTRICTEDARTICLES", "REVENUETON (RT)", "REVERSEIPI", "RFP", "RFQ", "RO/RO", "ROLL", "ROLLING", "ROUTE", "RUNNINGGEAR", "RVNX", "SAFE PORT ACT", "SANCTION", "S/D", "SCHEDULE B", "SEA BEE VESSELS", "SEA WAYBILL", "SEAWAYMAX VESSEL", "SEAWORTHINESS", "SECURE FREIGHT INITIATIVE (SFI)", "SECURITY LEVEL 1", "SECURITY LEVEL 2", "SECURITY LEVEL 3", "SED", "SERVICE", "SERVICE CONTRACT", "SHEX", "SHINC", "SHIP", "SHIP CHANDLER", "SHIP DEMURRAGE", "SHIP LOAD", "SHIP SECURITY OFFICER", "SHIP SECURITY PLAN", "SHIP TYPES", "SHIPMENT", "SHIPPER", "SHIPPERS ASSOCIATION", "SHIPPERS EXPORT DECLARATION SED EX DEC", "SHIPPERS INSTRUCTIONS", "SHIPPERS LETTER OF INSTRUCTIONS FOR ISSU", "SHIPS BELLS", "SHIPS MANIFEST", "SHIPS TACKLE", "SHORT SEA SHIPPING SSS (EUROPEANEU)", "SHORT TON (ST)", "SHRINK WRAP", "SIDE DOOR CONTAINER", "SIDE LOADER", "SIGHT DRAFT", "SIGTTO", "SKIDS", "SL/W", "SLEEPERS", "SLING", "SLIP", "SPA", "SPINE CAR", "SPOTTING", "SPREADER", "SSHEX", "STABILITY", "STACK CAR", "STACKTRAIN", "STANDARD INDUSTRIAL CLASSIFICATION (SIC)", "STANDARD INTERNATIONAL TRADE CLASSIFICAT", "STARBOARD", "STATUTE OF LIMITATION", "STC", "STCC", "STEAMSHIP CONFERENCE", "STEAMSHIP GUARANTEE", "STERN", "STEVEDORE", "STORE DOOR PICK UP DELIVERY", "STOWAGE", "STRADDLE CARRIER", "STRAIGHT BILL OF LADING", "STRIPPING", "STUFFING", "STW", "SUBROGATE", "SUEZMAX TANKER", "SUFFERANCE WHARF", "SUPPLY CHAIN", "SURCHARGE", "SURFACE TRANSPORTATION BOARD (STB)", "SURTAX", "T.&AMP,E.", "TARIFF", "TAIL", "TARE WEIGHT", "TARIFF (TRF.)", "TBN", "TELEX", "TEMPERATURE RECORDER", "TENDER", "TENOR", "TERMINAL", "TERMINAL CHARGE", "TERMS OF SALE", "TEU", "THIRD PARTY LOGISTICS (3PL)", "THROUGH RATE", "THROUGHPUT CHARGE", "TIME CHARTER", "TIME DRAFT", "TIR", "TON MILE", "TONNAGE", "TOP AIR DELIVERY", "TOWAGE", "TRACTOR", "TRADE ACCEPTANCE", "TRAFFIC", "TRAILER", "TRAMP LINE", "TRANSHIP", "TRANSHIPMENT PORT", "TRANSPORT", "TRANSPORTATION &AMP, EXIT (T&AMP,E)", "TRANSPORTATION WORKER IDENTIFICATION CRE", "TRUST RECEIPT", "TURNAROUND", "TWIST LOCKS", "TWO WAY PALLET", "UCP", "UFC", "U.S. CONSULAR INVOICE", "ULCC", "ULLAGE", "UNCLAIMED FREIGHT", "UNDERCHARGE", "UNDERWAY", "UNIFORM CUSTOMS AND PRACTICES FOR DOCUME", "UNIT LOAD", "UNIT TRAIN", "UNITIZATION", "UNLOADING", "USPPI UNITED STATES PRINCIPAL PARTY OF I", "VALIDATED EXPORT LICENSE", "VALUE ADDED TAX (VAT)", "VALIDATION", "VANNING", "VARIABLE COST", "VENTILATED CONTAINER", "VESSEL MANIFEST", "VESSEL SUPPLIES FOR IMMEDIATE EXPORTATIO", "VISA", "VIZ.", "VLCC", "VLFO VESSEL LOAD FREE OUT", "VOLUNTARY SHIP", "WAR RISK", "WORLD TRADE ORGANIZATION (WTO)", "W.M. (W/M)", "W.T.L.", "WAREHOUSE", "WAREHOUSE ENTRY", "WAREHOUSE WITHDRAWAL FOR TRANSPORTATION", "WAREHOUSEWITHDRAWAL FOR TRANSPORTATION (", "WAREHOUSING", "WAYBILL (WB)", "WDT&AMP,E)", "WEIGHT CARGO", "WEIGHTS AND MEASURES/MEASUREMENT TON", "WELL CAR", "WHARF", "WHARFAGE (WHFGE.)", "WIBON", "YARD", "ZULU TIME"}

below is my code
VB.NET:
  Private Sub RichTextBox1_TextChanged(sender As Object, e As EventArgs) Handles RichTextBox1.TextChanged

            For Each searchword As String In ArrayValue ' added
                Dim index As Integer = 0
                While index <> -1
                    index = RichTextBox1.Text.IndexOf(searchword, index)
                    If index <> -1 Then
                        If index = RichTextBox1.Text.Length - searchword.Length - 1 Then
                            RichTextBox1.SelectionStart = index
                            RichTextBox1.SelectionLength = searchword.Length
                            RichTextBox1.SelectionColor = Color.Black
                            RichTextBox1.SelectionStart = RichTextBox1.Text.Length
                            Exit Sub
                        Else
                            index += 1
                        End If
                    Else
                        RichTextBox1.SelectionColor = Color.Red
                    End If
                End While
            Next
        End Sub
    End Class

Thanks in Advance
 

ryoka012

Active member
Joined
Oct 13, 2011
Messages
32
Programming Experience
Beginner
Hi JohnH,

Thanks for the reply.

I have edited my code below, but it does flicker and hang a little bit.

VB.NET:
 For Each searchword As String In ArrayValue ' added
                Dim index As Integer = 0
                  index = RichTextBox1.Text.IndexOf(searchword, index)
                Label1.Text = index
                If index = -1 Then
                      RichTextBox1.SelectionStart = index
                    RichTextBox1.SelectionLength = searchword.Length
                    RichTextBox1.SelectionColor = Color.Red
                    RichTextBox1.SelectionStart = RichTextBox1.Text.Length
                    Exit Sub
           
                End If
             
            Next ' added
 
Last edited:

cjard

Well-known member
Joined
Apr 25, 2006
Messages
7,052
Programming Experience
10+
Think about what it's doing for a second though. Every time you change as small amount as ONE CHARACTER, your code will search the text box contents (lets assume it is 1 megabyte of text) for each one of 740 words.

That's 740 megabytes of text searched every time you press a key!

No wonder the program hangs


So tell me, how are you going to design your program differently, more efficient? Here's a tip: your code should watch the changes made to textbox, and only be interested at certain times, like when a whole new word is added, not when youre still typing the middle of a word. Then it should go and get only the new word that was added, not all the other megabyte of text. Only if that new word is in the list (which can be a dictionary lookup) then colour it, and the rich textbox will remember that it is coloured, forever more. It doesnt need you to continuously change the colour..
 

ryoka012

Active member
Joined
Oct 13, 2011
Messages
32
Programming Experience
Beginner
Hi,

@cjard
Thanks for the input. i have updated my code
Please see below code for someone who this kind of approach.

VB.NET:
     Dim S As Integer = [COLOR=#333333]ArrayValue[/COLOR].SelectionStart
        Dim ArrayValue() As String = [COLOR=#333333]ArrayValue[/COLOR].Split(" ")
        For i As Integer = 0 To ArrayValue.Length - 1
            Dim str As String = ArrayValue(i)
            Dim start As Integer = S - str.Length - 1
            If (start >= 0) Then
                If ([COLOR=#333333]RichTextBox1[/COLOR].Text.Substring(start, str.Length).Equals(str)) Then
                     [COLOR=#333333]RichTextBox1[/COLOR].SelectionStart = start
                     [COLOR=#333333]RichTextBox1[/COLOR].SelectionLength = str.Length
                     [COLOR=#333333]RichTextBox1[/COLOR].SelectionColor = Color.Black
                     [COLOR=#333333]RichTextBox1[/COLOR].SelectionStart = S
                     [COLOR=#333333]RichTextBox1[/COLOR].SelectionLength = 0
                End If
            End If
        Next
         [COLOR=#333333]RichTextBox1[/COLOR].SelectionColor = Color.Red
]
 
Top Bottom