views:

54

answers:

3

I have a textbox filled with boolean. How do I put the contents into an array?

Thanks.

A: 

The textbox has a string representation of a Boolean; you need to cast it:

bool myBool = bool.Parse(myTbox.Text);

And then put it in your array.

Pierreten
+3  A: 

Is it a string like this?

True False True True False False True

If so, try this:

bool[] contents = myTextBox.Text.Split(' ') // or whatever your split char is
    .Select(s => bool.Parse(s))
    .ToArray();

A more robust approach would be to ignore invalid values by using bool.TryParse:

bool[] contents = myTextBox.Text.Split(' ') // or whatever
    .Where(s => { bool discard; return bool.TryParse(s, out discard); })
    .Select(s => bool.Parse(s)) // a little redundant, but clean
    .ToArray();
Dan Tao
A: 

Another way is

 bool myBool;
 if (!bool.TryParse(myTbox.Text, out myBool))
  MessageBox.Show("Cannot convert text to bool.");