包含文本框到数组 - C#

问题描述:

我有一个文本框填充布尔值。我如何将内容放入数组中?包含文本框到数组 - C#

谢谢。

+0

请澄清你的问题:一个文本框包含一个值,而一个数组包含很多值。 – Polyfun 2010-05-19 15:32:26

+0

假设,复选框将是布尔值更好的选择。 – Alex 2010-05-19 15:38:40

+0

你只是弄错了我的心... – 2010-05-19 15:58:22

该文本框具有布尔型的字符串表示形式;你需要施放它:

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

然后把它放在你的数组中。

它是这样的字符串吗?

True False True True False False True 

如果是的话,试试这个:

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

更健壮的方法是忽略无效的值,通过使用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(); 

另一种方式是

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