[英]C# WinForms - How to (do something) with several textboxes between 2 values
I have a form, where a 'user' inputs values into several textboxes and if the values are between certain ranges I want it to do something. 我有一个表单,其中“用户”将值输入到多个文本框中,并且如果值在某些范围之间,我希望它执行某些操作。
Is it possible to check multiple textboxes simultaneously as opposed to having them checked like so: 是否可以同时检查多个文本框,而不是像这样检查它们:
if (int.Parse(textbox1.Text) >= 100 && int.Parse(textbox1.Text) <= 2000)
{
mylist.Add(int.parse(textbox1.text));
}
if (int.Parse(textbox2.Text) >= 100 && int.Parse(textbox2.Text) <= 2000)
{
mylist.Add(int.parse(textbox1.text));
}
if (int.Parse(textbox3.Text) >= 100 && int.Parse(textbox3.Text) <= 2000)
{
mylist.Add(int.parse(textbox3.text));
}
One possibility would be to put them in a list: 一种可能性是将它们放在列表中:
var textboxes = new List<TextBox>(new[] { textbox1, textbox2, textbox3 });
and then loop through this list and probably parse the value only once: 然后遍历此列表,可能只解析一次该值:
foreach (var t in textboxes)
{
int value = int.Parse(t.Text);
if (value >= 100 && value <= 2000)
{
mylist.Add(value);
}
}
or if you prefer using LINQ you could also do this one liner: 或者,如果您更喜欢使用LINQ,也可以执行以下操作:
IList<int> mylist = textboxes
.Select(t => int.Parse(t.Value))
.Where(value => value >= 100 && value <= 2000)
.ToList();
Extract method: 提取方法:
public void AddValue(string text, List<int> list)
{
var value = int.Parse(test);
if (value >= 100 && value <= 2000)
{
list.Add(value);
}
}
And call it: 并称之为:
var list = new List<int>();
AddValue(textbox1.Text, list);
AddValue(textbox2.Text, list);
AddValue(textbox3.Text, list);
You could write a simple boolean method that does this work on a textbox passed to it and tells the calling code if the parsing is successful 您可以编写一个简单的布尔方法,对传递给它的文本框执行此操作,并告诉调用代码解析是否成功
private bool ParseText(TextBox txt, List<int> theList)
{
int value;
if(Int32.TryParse(txt.Text, out value))
{
if(value >= 100 && value <= 2000)
{
theList.Add(value);
return true;
}
}
return false;
}
Now you could call this method 现在您可以调用此方法
if(!ParseText(textBox1, mylist))
MessageBox.Show("Invalid value in TextBox1");
if(!ParseText(textBox2, mylist))
MessageBox.Show("Invalid value in TextBox2");
if(!ParseText(textBox3, mylist))
MessageBox.Show("Invalid value in TextBox3");
Notice that a textbox whose text is expected to be an integer but is typed by the user should be always parsed using Int32.TryParse
instead of Parse
because Parse raises an exception if the text cannot be converted to an integer 请注意,应始终使用
Int32.TryParse
而不是Parse
解析其文本应为整数但由用户键入的文本框,因为如果文本无法转换为整数,则Parse引发异常
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.