c# - changing a group of textbox controls to ReadOnly = false
问题描述
I have a group of textbox controls which I want to change out of ReadOnly. My code snippet is below. The ReadOnly line gives error "control does not have a definition of ReadOnly..." I believe the issue has to do with the ReadOnly functionality being in the TextBoxBase class. How can I get around this and have access to the TextBoxBase class?
foreach (Control c in fraPParameters.Controls)
{
if (c is Label)
{
c.Visible = false;
c.Text = string.Empty;
c.Tag = string.Empty;
tt.SetToolTip(c, null);
}
if (c is TextBox)
{
c.Visible = false;
c.ReadOnly = false;
c.Text = string.Empty;
c.Tag = string.Empty;
tt.SetToolTip(c, null);
c.BackColor = Color.White;
}
}
解决方案
使用类型模式来测试表达式是否可以转换为指定的类型,如果可以,则将其转换为该类型的变量。
在使用类型模式执行模式匹配时,is 测试表达式是否可以转换为指定的类型,如果可以,则将其转换为该类型的变量。它是 is 语句的直接扩展,可实现简洁的类型评估和转换。is 类型模式的一般形式是:
expr is type varname
例子
if (sender is TextBox textBox)
{
textBox.Visible = false;
textBox.ReadOnly = false;
textBox.Text = string.Empty;
textBox.Tag = string.Empty;
...
此外,您可能只想使用带有模式匹配的 switch 语句,正如Callum Watkins在评论中提到的那样
foreach (Control c in fraPParameters.Controls)
{
switch (c)
{
case TextBox textbox:
textbox.Visible = false;
textbox.ReadOnly = false;
textbox.Text = string.Empty;
textbox.Tag = string.Empty;
//...
break;
case Label label:
label.Visible = false;
label.Text = string.Empty;
label.Tag = string.Empty;
//...
break;
}
}
其他资源
检查对象是否与给定类型兼容,或者(从 C# 7.0 开始)针对模式测试表达式。
推荐阅读
- windows - Lilypond for Windows 的安装问题
- google-maps - Google Elevation API 路径参数错误
- python - tkinter 窗口间拖放支持
- sql - 将 SQL Server 代码转换为 Firebird 会产生“令牌未知”错误
- pentaho - 将值传递给作业执行器 pentaho
- java - 具有奇数 arrayList 大小的 Mergesort 将数字稍微混合
- flutter - Flutter 插件 onActivityResult 从未调用过
- java - Jersey REST-Servlet 中的 RolesAllowed 注释不起作用
- javascript - Discord Bot 设置命令,在不同的消息后保存消息
- javascript - 客人结账时的 Opencart JS 验证