gpt4 book ai didi

c# - 将一组文本框控件更改为 ReadOnly = false

转载 作者:太空宇宙 更新时间:2023-11-03 19:39:36 25 4
gpt4 key购买 nike

我有一组文本框控件,我想将其更改为只读。我的代码片段如下。 ReadOnly 行给出错误“控件没有 ReadOnly 的定义...”我相信这个问题与 TextBoxBase 类中的 ReadOnly 功能有关。我怎样才能解决这个问题并访问 TextBoxBase 类?

        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;
}
}

最佳答案

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

When using the type pattern to perform pattern matching, is tests whether an expression can be converted to a specified type and, if it can be, casts it to a variable of that type. It is a straightforward extension of the is statement that enables concise type evaluation and conversion. The general form of the is type pattern 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;

}
}

其他资源

is (C# Reference)

Checks if an object is compatible with a given type, or (starting with C# 7.0) tests an expression against a pattern.

Using pattern matching switch statements

关于c# - 将一组文本框控件更改为 ReadOnly = false,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55506299/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com