所以我有一个脚本动态生成的表单,为每个作为参数拉出的字符串都有一个标签和一个文本框。我希望用户填写每个文本框,然后选择确定按钮。之后我想处理每个文本框的每个项目。在只有一个项目之前,我写了一个非常简单的属性来获取文本框的值。
Public string Text { get { return textbox1.Text; } }
我希望通过动态数量的文本框,我可以做一些优雅的事情。
Public string [] Text { get { return **Each text box text as an array**; } }
我已经考虑了一段时间,我想不出一种优雅的方式来设置它,这里是文本框添加到表单的方式......
string[] keywords = Environment.GetCommandLineArgs();
int placement = 10;
foreach (string keyword in keywords)
{
if (keyword == keywords[0])
continue;
Label lbl = new Label();
lbl.Text = keyword;
lbl.Top = placement;
this.Controls.Add(lbl);
TextBox txt = new TextBox();
txt.Top = placement;
txt.Left = 100;
this.Controls.Add(txt);
placement += 20;
}
我可以在表单关闭时循环遍历每个文本框的文本,并使用值填充公共数组,但我宁愿想出一些更优雅的东西,并且不再习惯用武力做事。谁有任何关于如何实现这一目标的好主意?我想我可以将所有文本框添加到数组中,然后让字符串属性以某种方式获取指定文本框的文本,或者只是将文本框数组改为公共属性。有没有办法写这样的东西......
Public string [] Text { get { return TextBoxArray[**value trying to be gotten**].Text; } }
或者这对于一个属性来说是多少而需要成为一种方法呢?任何人有任何其他想法?我意识到这是一个微不足道的问题,并且可以通过多种方式解决,我只是希望通过很酷的方式拓宽我的视野来完成这样的事情。
答案 0 :(得分:3)
其他选项可能更好,但这可能是最直接和最简洁的:(使用LINQ,添加using System.Linq;
,需要.NET 3.5或更高版本)
public string[] Text { get { return Controls.OfType<TextBox>().Select(x => x.Text).ToArray(); } }
这与AlejoBrz的解决方案非常相似,但使用LINQ更加清晰简洁。
答案 1 :(得分:1)
从技术上讲,属性只是getter / setter方法的语法糖 - 所以属性可以做任何方法可以做的事情(但大多数时候它应该是SHOULDNT!)
我只是将所有文本框添加到Dictionary对象中,假设您的命令行参数不能重复。
基本上在启动时:
创建一个:
Dictionary<string, TextBox> boxes;
使用命令参数作为键
在启动代码中添加文本框boxes.Add(commandName, newTextBox);
然后在你的getter中你可以使用
访问字典boxes[commandName]
将返回您可以操作的文本框。这当然是强类型的:)
以下是一些示例代码:
string[] keywords = Environment.GetCommandLineArgs();
Dictionary<string, TextBox> boxes = new Dictionary<string, TextBox>();
int placement = 10;
foreach (string keyword in keywords)
{
if (keyword == keywords[0])
continue;
Label lbl = new Label();
lbl.Text = keyword;
lbl.Top = placement;
this.Controls.Add(lbl);
TextBox txt = new TextBox();
txt.Top = placement;
txt.Left = 100;
this.Controls.Add(txt);
placement += 20;
boxes.Add(keyword, txt);
}
然后我想你不需要一个吸气剂 - 只需让盒子字典可见
public Dictionary<string, TextBox> Boxes { get { return boxes; } }
如果您对文本框不感兴趣,只想要值:
public Dictionary<string, string> Arguments
{
get
{
Dictionary<string, string> vals = new Dictionary<string, string>();
foreach(KeyValuePair<string, TextBox> kvp in boxes)
{
vals.Add(kvp.Key, kvp.Value.Text);
}
return vals;
}
}
答案 2 :(得分:1)
这是一个想法:
Public System.Collections.Generic.List<string> Text {
get {
System.Collections.Generic.List<string> returnValue = new string[textBoxCount];
foreach (Control ctrl in this.Controls)
if (ctrl.GetType() == typeof(TextBox))
returnValue.Add(((TextBox)ctrl).Text);
return returnValue;
}
}
当然,它会遍历所有控件,但至少你不必将它们保存在某种变量中,例如System.Collections.Generic.List。或者你可以这样做,并在这个foreach删除if。