2 回答
TA贡献1866条经验 获得超5个赞
像这样的东西:
string val = (this.Controls[viewIdentifier] as TextBox)?.Text;
这里
我们用它的名字
Control
在里面寻找Controls
——viewIdentifier
as TextBox
:尝试将控件转换为TextBox
(null
如果不是TextBox
)?.Text
如果转换成功,则获取Text
(null
否则)
编辑如果需要is
(让我们修改当前代码),您可以使用模式匹配(C# 7.0)实现例程:
string viewIdentifier = "MyControlName";
string val = null;
// viewIdentifier is String, when this.Controls[viewIdentifier] is Control
// ... is TextBox textbox: if left side matches TextBox pattern
// then textbox is a matched pattern to work with
if (this.Controls[viewIdentifier] is TextBox textbox) {
val = textbox.Text;
}
TA贡献1795条经验 获得超7个赞
string viewIdentifier= "MyControlName";
var hasTextBoxWithThisName = this.Controls.OfType<TextBox>().Any(c => c.Name == viewIdentifier);
编辑:
var t = this.Controls.OfType<TextBox>()
.SingleOrDefault(c => c.Name == viewIdentifier);
if (t != null)
{
var text = t.Text;
}
- 2 回答
- 0 关注
- 317 浏览
添加回答
举报