2016-10-11 90 views
0

這是在Microsoft Visual Studio 2015中。我使用Visual Basic代碼,並且我試圖在某人輸入名稱在txtPokemonInput,它驗證它是一個實際的名稱。當我運行的代碼,並鍵入 「阿布拉」 到文本框中,然後單擊cmdCalculate,我得到這個錯誤:在Microsoft.VisualBasic.dll中發生未處理的類型'System.InvalidCastException'的異常。

An unhandled exception of type 'System.InvalidCastException' occurred in Microsoft.VisualBasic.dll Additional information: Conversion from string "Bellsprout" to type 'Boolean' is not valid.

這裏是代碼:

Option Compare Text 
Public Class Form1 
    Private Sub cmdCalculate_Click(sender As Object, e As EventArgs) Handles  
cmdCalculate.Click 
    If txtPokemonInput.Text <> "Abra" Or "Bellsprout" Then 
     MsgBox("Please input an actual Pokemon name.") 
    End If 
End Sub 
End Class 
+0

多數民衆贊成那不是多麼'或'的作品,它不會甚至編譯下選項嚴格 – Plutonix

回答

1

此:

If txtPokemonInput.Text <> "Abra" Or "Bellsprout" Then 

沒有做你想做的事。它實際上做的是嘗試對「Abra」和「Bellsprout」執行邏輯或操作,然後將布爾結果與Text屬性進行比較。用Strings執行布爾邏輯是導致無效轉換的原因。該代碼做你真正想做的事是這樣的:

If txtPokemonInput.Text <> "Abra" AndAlso txtPokemonInput.Text <> "Bellsprout" Then 

注意,這是一個合乎邏輯的而非邏輯OR和AndAlso運算符優先於And運營商使用的短路短。

我強烈建議你在你的項目屬性和IDE選項中設置Option Strict On,這樣所有未來的項目默認會有On。這不會阻止你犯這樣的錯誤,但它會將它們標記爲編譯錯誤,而不是讓它們在運行時被抓到。

+0

謝謝!我習慣於使用Visual Basic 6.0,這是他在我的學校,所以仍然有些東西我需要習慣:) –

+0

@SamValenzuela,您仍然會遇到與'VB 6'相同的錯誤。 –

0

我假設你想驗證2個以上的名字。有更好的方法來驗證數據庫,但這應該適用於您。我從wikipedia中獲取了這個口袋妖怪名稱列表,並使用Notepad ++將其格式化爲一個數組字符串。

Private Sub cmdCalculate_Click(sender As Object, e As EventArgs) Handles cmdCalculate.Click 

    ' Trim off any leading or trailing spaces 
    txtPokemonInput.Text = txtPokemonInput.Text.trim 
    ' Call the function and pass the search string. The function returns true if it found the name and false if it did not 
    If ValidatePokemonName(txtPokemonInput.Text) = False Then MsgBox("Please input an actual Pokemon name.") 

End Sub 


Private Function ValidatePokemonName(ByVal CheckName As String) As Boolean 

    CheckName = CheckName.ToLower ' convert the user text to all lower case. This will allow the program to ignore case 

    ' Create an array of valid names 
    Dim ValidNames() As String = {"abomasnow", "abra", "absol", "accelgor", "aegislash", "aerodactyl", "aggron", "aipom", "alakazam", "alomomola", "altaria", "amaura", "ambipom" _ 
            , "amoonguss", "ampharos", "anorith", "arbok", "arcanine", "arceusi", "archen", "archeops", "ariados", "armaldo", "aromatisse", "aron", "articuno" _ 
           , "audino", "aurorus", "avalugg", "axew", "azelf", "azumarill", "azurilln", "bagon", "baltoy", "banette", "barbaracle", "barboach", "basculin", "bastiodon" _ 
           , "bayleef", "beartic", "beautifly", "beedrill", "beheeyem", "beldum", "bellossom", "bellsprout", "bergmite", "bewear", "bibarel", "bidoof", "binacle" _ 
           , "bisharp", "blastoise", "blaziken", "blissey", "blitzle", "boldore", "bonslyp", "bouffalant", "bounsweet", "braixen", "braviary", "breloom", "brionne" _ 
           , "bronzong", "bronzor", "bruxish", "budewp", "buizel", "bulbasaur", "buneary", "bunnelby", "burmy", "butterfree", "cacnea", "cacturne", "camerupt", "carbink" _ 
           , "carnivine", "carracosta", "carvanha", "cascoon", "castform", "caterpie", "celebii", "chandelure", "chansey", "charizard", "charjabug", "charmander", "charmeleon" _ 
           , "chatot", "cherrim", "cherubi", "chesnaught", "chespin", "chikorita", "chimchar", "chimecho", "chinchou", "chinglingp", "cinccino", "clamperl", "clauncher" _ 
           , "clawitzer", "claydol", "clefable", "clefairy", "cleffa", "cloyster", "cobalion", "cofagrigus", "combee", "combusken", "comfey", "conkeldurr", "corphish", "corsola" _ 
           , "cottonee", "crabrawler", "cradily", "cranidos", "crawdaunt", "cresselia", "croagunk", "crobat", "croconaw", "crustle", "cryogonal", "cubchoo", "cubone", "cutiefly" _ 
           , "cyndaquil", "darkraii", "darmanitan", "dartrix", "darumaka", "dedenne", "deerling", "deino", "delcatty", "delibird", "delphox", "deoxyso", "dewgong", "dewott" _ 
           , "dialga", "dianciei", "diggersby", "diglett", "ditto", "dodrio", "doduo", "donphan", "doublade", "dragalge", "dragonair", "dragonite", "drampa", "drapion", "dratini" _ 
           , "drifblim", "drifloon", "drilbur", "drowzee", "druddigon", "ducklett", "dugtrio", "dunsparce", "duosion", "durant", "dusclops", "dusknoir", "duskull", "dustox" _ 
           , "dwebble", "eelektrik", "eelektross", "eevee", "ekans", "electabuzz", "electivire", "electrike", "electrode", "elekid", "elgyem", "emboar", "emolga", "empoleon" _ 
           , "entei", "escavalier", "espeon", "espurr", "excadrill", "exeggcute", "exeggutor", "exploud", "farfetch'd", "fearow", "feebas", "fennekin", "feraligatr", "ferroseed" _ 
           , "ferrothorn", "finneon", "flaaffy", "flabébé", "flareon", "fletchinder", "fletchling", "floatzel", "floette", "florges", "flygon", "fomantis", "foongus", "forretress" _ 
           , "fraxure", "frillish", "froakie", "frogadier", "froslass", "furfrou", "furret", "gabite", "gallade", "galvantula", "garbodor", "garchomp", "gardevoir", "gastly", "gastrodon" _ 
           , "genesecti", "gengar", "geodude", "gible", "gigalith", "girafarig", "giratina", "glaceon", "glalie", "glameow", "gligar", "gliscor", "gloom", "gogoat", "golbat", "goldeen" _ 
           , "golduck", "golem", "golett", "golurk", "goodra", "goomy", "gorebyss", "gothita", "gothitelle", "gothorita", "gourgeist", "granbull", "graveler", "greninja", "grimer" _ 
           , "grotle", "groudon", "grovyle", "growlithe", "grubbin", "grumpig", "gulpin", "gumshoos", "gurdurr", "gyarados", "happinyp", "hariyama", "haunter", "hawlucha", "haxorus" _ 
           , "heatmor", "heatran", "heliolisk", "helioptile", "heracross", "herdier", "hippopotas", "hippowdon", "hitmonchan", "hitmonlee", "hitmontop", "ho-ohk", "honchkrow", "honedge" _ 
           , "hoopai", "hoothoot", "hoppip", "horsea", "houndoom", "houndour", "huntail", "hydreigon", "hypno", "igglybuff", "illumise", "infernape", "inkay", "ivysaur", "jangmo-o" _ 
           , "jellicent", "jigglypuff", "jirachii", "jolteon", "joltik", "jumpluff", "jynx", "kabuto", "kabutops", "kadabra", "kakuna", "kangaskhan", "karrablast", "kecleon", "keldeoi" _ 
           , "kingdra", "kingler", "kirlia", "klang", "klefki", "klink", "klinklang", "koffing", "komala", "krabby", "kricketot", "kricketune", "krokorok", "krookodile", "kyogre", "kyurem" _ 
           , "lairon", "lampent", "landorus", "lanturn", "lapras", "larvesta", "larvitar", "latias", "latios", "leafeon", "leavanny", "ledian", "ledyba", "lickilicky", "lickitung", "liepard" _ 
           , "lileep", "lilligant", "lillipup", "linoone", "litleo", "litten", "litwick", "lombre", "lopunny", "lotad", "loudred", "lucario", "ludicolo", "lugiaj", "lumineon", "lunala" _ 
           , "lunatone", "lurantis", "luvdisc", "luxio", "luxray", "lycanwolf", "machamp", "machoke", "machop", "magby", "magcargo", "magearnav", "magikarp", "magmar", "magmortar" _ 
           , "magnemite", "magneton", "magnezone", "makuhita", "malamar", "mamoswine", "manaphyi", "mandibuzz", "manectric", "mankey", "mantine", "mantykep", "maractus", "mareep" _ 
           , "marill", "marowak", "marshtomp", "masquerain", "mawile", "medicham", "meditite", "meganium", "meloettai", "meowstic", "meowth", "mesprit", "metagross", "metang", "metapod" _ 
           , "mewi", "mewtwo", "mienfoo", "mienshao", "mightyena", "milotic", "miltank", "mime jr.p", "mimikyu", "minccino", "minior", "minun", "misdreavus", "mismagius", "moltres", _ 
            "monferno", "morelull", "mothim", "mr. mime", "mudbray", "mudkip", "mudsdale", "muk", "munchlaxp", "munna", "murkrow", "musharna", "natu", "nidoking", "nidoqueen", "nidoran" _ 
           , "nidoran?", "nidorina", "nidorino", "nincada", "ninetales", "ninjask", "noctowl", "noibat", "noivern", "nosepass", "numel", "nuzleaf", "octillery", "oddish", "omanyte", "omastar" _ 
           , "onix", "oranguru", "oricorio", "oshawott", "pachirisu", "palkia", "palossand", "palpitoad", "pancham", "pangoro", "panpour", "pansage", "pansear", "paras", "parasect" _ 
           , "passimian", "patrat", "pawniard", "pelipper", "persian", "petilil", "phanpy", "phantump", "phioneq", "pichu", "pidgeot", "pidgeotto", "pidgey", "pidove", "pignite", "pikachu" _ 
           , "pikipek", "piloswine", "pineco", "pinsir", "piplup", "plusle", "politoed", "poliwag", "poliwhirl", "poliwrath", "ponyta", "poochyena", "popplio", "porygon", "porygon-z" _ 
           , "porygon", "primeape", "prinplup", "probopass", "psyduck", "pumpkaboo", "pupitar", "purrloin", "purugly", "pyroar", "pyukumuku", "quagsire", "quilava", "quilladin", "qwilfish" _ 
           , "raichu", "raikou", "ralts", "rampardos", "rapidash", "raticate", "rattata", "rayquaza", "regice", "regigigas", "regirock", "registeel", "relicanth", "remoraid", "reshiram" _ 
           , "reuniclus", "rhydon", "rhyhorn", "rhyperior", "riolu", "rockruff", "roggenrola", "roselia", "roserade", "rotom", "rowlet", "rufflet", "sableye", "salamence", "salandit" _ 
           , "samurott", "sandile", "sandshrew", "sandslash", "sandygast", "sawk", "sawsbuck", "scatterbug", "sceptile", "scizor", "scolipede", "scrafty", "scraggy", "scyther", "seadra" _ 
           , "seaking", "sealeo", "seedot", "seel", "seismitoad", "sentret", "serperior", "servine", "seviper", "sewaddle", "sharpedo", "shaymini", "shedinja", "shelgon", "shellder" _ 
           , "shellos", "shelmet", "shieldon", "shiftry", "shinx", "shroomish", "shuckle", "shuppet", "sigilyph", "silcoon", "simipour", "simisage", "simisear", "skarmory", "skiddo" _ 
           , "skiploom", "skitty", "skorupi", "skrelp", "skuntank", "slaking", "slakoth", "sliggoo", "slowbro", "slowking", "slowpoke", "slugma", "slurpuff", "smeargle", "smoochum" _ 
           , "sneasel", "snivy", "snorlax", "snorunt", "snover", "snubbull", "solgaleo", "solosis", "solrock", "spearow", "spewpa", "spheal", "spinarak", "spinda", "spiritomb", "spoink" _ 
           , "spritzee", "squirtle", "stantler", "staraptor", "staravia", "starly", "starmie", "staryu", "steelix", "stoutland", "stufful", "stunfisk", "stunky", "sudowoodo", "suicune" _ 
           , "sunflora", "sunkern", "surskit", "swablu", "swadloon", "swalot", "swampert", "swanna", "swellow", "swinub", "swirlix", "swoobat", "sylveon", "taillow", "talonflame" _ 
           , "tangela", "tangrowth", "tapu koko", "tauros", "teddiursa", "tentacool", "tentacruel", "tepig", "terrakion", "throh", "thundurus", "timburr", "tirtouga", "togedemaru" _ 
           , "togekiss", "togepi", "togetic", "torchic", "torkoal", "tornadus", "torracat", "torterra", "totodile", "toxicroak", "tranquill", "trapinch", "treecko", "trevenant", "tropius" _ 
           , "trubbish", "turtonator", "turtwig", "tympole", "tynamo", "type: null", "typhlosion", "tyranitar", "tyrantrum", "tyrogue", "tyrunt", "umbreon", "unfezant", "unown", "ursaring" _ 
           , "uxie", "vanillish", "vanillite", "vanilluxe", "vaporeon", "venipede", "venomoth", "venonat", "venusaur", "vespiquen", "vibrava", "victinii", "victreebel", "vigoroth", "vikavolt" _ 
           , "vileplume", "virizion", "vivillon", "volbeat", "volcanioni", "volcarona", "voltorb", "vullaby", "vulpix", "wailmer", "wailord", "walrein", "wartortle", "watchog", "weavile" _ 
           , "weedle", "weepinbell", "weezing", "whimsicott", "whirlipede", "whiscash", "whismur", "wigglytuff", "wimpod", "wingull", "wishiwashi", "wobbuffet", "woobat", "wooper", "wormadam" _ 
           , "wurmple", "wynautn", "xatu", "xerneas", "yamask", "yanma", "yanmega", "yungoos", "yveltal", "zangoose", "zapdos", "zebstrika", "zekrom", "zigzagoon", "zoroarku", "zoruat" _ 
           , "zubat", "zweilous", "zygarde"} 

    Dim FoundMatch As Boolean = False ' Create a flag we can set if we find the search string 

    For i As Integer = 0 To ValidNames.Length - 1 ' Step through each name and compare it to the user entry 

     If ValidNames(i) = CheckName Then FoundMatch = True : Exit For 'If it matches set the flag to true and exit the for loop. 

    Next 

    Return FoundMatch ' Return the flag 


End Function