如果值为 false,如何在 c# 中禁用按钮

本文关键字:按钮 false 如果 | 更新日期: 2023-09-27 18:34:15

我正在创建一个剪贴板编辑程序,但在使用"复制"按钮时遇到错误。如果从中复制到剪贴板内容的文本框为空,则我得到"未处理参数空异常"。我知道这是因为它从中复制文本的文本框是空的。我想编写一种方法,如果文本框为空,则禁用按钮。下面是此按钮的代码:

 // Copies the text in the text box to the clipboard.
    private void copyButton_Click(object sender, EventArgs e)
    {
        Clipboard.SetText(textClipboard.Text);
    }

感谢任何和所有的帮助。如果我缺少更多详细信息,请告诉我,以便我添加它们。

如果值为 false,如何在 c# 中禁用按钮

您必须首先将按钮设置为禁用。

然后,您可以使用该代码检测文本框中的更改:

    private void textClipboard_TextChanged(object sender, EventArgs e)
    {
        copyButton.Enabled = textClipboard.Text.Length > 0;
    }

你应该检查空值:

 // Copies the text in the text box to the clipboard.
    private void private void textClipboard_LostFocus(object sender, System.EventArgs e)
    {
        if(!string.IsNullOrEmpty(textClipboard.Text)
        {
            Clipboard.SetText(textClipboard.Text);
        }
        else
        {
          copyButton.Enabled = false; //Set to disabled
        }
    }

最初可以将 button.enabled 设置为 false,并将 KeyUp 事件添加到文本框中:

    private void textClipboard_KeyUp(object sender, KeyEventArgs e)
    {
        copyButton.Enabled = !string.IsNullOrEmpty(textBox1.Text);
    }