Monday, February 7, 2011

invalid cast exception, storing textbox value in brackets

textbox1.text = "6916092, 15195440, 16107657, 1836924, 3758726, 12566463, 7526079, 7405793, 6945974, 241502, 2296476, 5130294, 3102017, 7324121, 14993507"

ColorDialog1.CustomColors = New Integer() {TextBox1.Text}

i am getting an InvalidCastException

how do i insert the value of textbox1.text into those brackets in vb.net?

  • If you're using Visual Studio 2008 try the following

    Dim numberStrings = TextBox1.Text.Split(","c).Select(Function(x) x.Trim()))
    ColorDialog1.CustomColors = numberStrings.Select(Function(x) CInt(x)).ToArray()
    

    Here's a version for 2005

    Dim list as New List(Of String)(TextBox1.Text.Split(","c)
    Dim numbers as New List(Of Integer)
    For i as Integer = 0 to list.Count - 1
      list(i) = list(i).Trim()
      numbers.Add(CInt(list(i))
    Next
    ColorDialag1.CustomColors = numbers.ToArray()
    
    I__ : it says 1 dimensional array cannot be converter to CHAR
    I__ : the error pertains to this New String() {","}
    JaredPar : @avrohom try again. I updated the code.
    I__ : Unable to cast object of type 'WhereSelectArrayIterator`2[System.String,System.String]' to type 'System.String[]'. for the second line of the first block of code
    Marc : You're stuffing a IEnumerable into a String[], which won't work. Toss a .ToArray() at the end of your trim line.
    JaredPar : @avrohom, hah. That's what I get for not trying it in a compiler. I updated it again, it should work this time
    I__ : excellent thank you very much it works. i have another problem that i will post up right now
    Marc : @Jared - may want to specify .NET 3.5 versus 2.0 instead of the IDE versions, since you can target 2.0 (no LINQ available) just fine with VS 2008
    JaredPar : @Marc, actually you can use LINQ just fine while targeting 2.0. As long as there are appropriate bindable extension methods LINQ works fine without System.Core. LINQBridge is the most popular 2.0 library although there are a couple available.
    From JaredPar
  • string s = "1,2,3,4";
    int[] n = Array.ConvertAll(s.Split(','), (item => Convert.ToInt32(item)));
    

0 comments:

Post a Comment