首页 > 解决方案 > 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;
            }
        }

标签: c#

解决方案


使用类型模式来测试表达式是否可以转换为指定的类型,如果可以,则将其转换为该类型的变量。

在使用类型模式执行模式匹配时,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# 参考)

检查对象是否与给定类型兼容,或者(从 C# 7.0 开始)针对模式测试表达式。

使用模式匹配 switch 语句


推荐阅读