字符串数组属性返回窗体上文本框的文本属性
本文关键字:文本 属性 窗体 数组 返回 字符串 | 更新日期: 2023-09-27 18:34:25
所以我有一个由脚本动态生成的表单,为每个作为参数拉取的字符串都有一个标签和一个文本框。 我希望用户填写每个文本框,然后选择"确定"按钮。 之后,我想处理每个文本框的每个项目。 以前只有 1 个项目时,我编写了一个非常简单的属性来获取文本框的值。
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; } }
或者这对一个属性来说很重要,需要成为一种方法? 还有什么想法吗? 我意识到这是一个微不足道的问题,可以通过多种方式解决,我只是想拓宽我的视野,以很酷的方式完成这样的事情。
其他选项可能更好,但这可能是最直接和简洁的: (使用 LINQ,添加using System.Linq;
,需要 .NET 3.5 或更高版本(
public string[] Text { get { return Controls.OfType<TextBox>().Select(x => x.Text).ToArray(); } }
这与 AlejoBrz 的解决方案非常相似,但使用 LINQ 更加清晰简洁。
这里有一个想法:
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(中的内存中。或者你可以这样做,并在此删除if。
从技术上讲,属性只是 getter/setter 方法的语法糖 - 因此属性可以做方法可以做的任何事情(但大多数时候它不应该!
我只是将所有文本框添加到字典对象中,假设您的命令行参数无法复制。
基本上在启动时:
创建:
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);
}
然后我想你不需要 getter - 只需使框字典可见即可
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;
}
}