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

时间:2013-10-08 00:17:21

标签: c# debugging button

我正在创建剪贴板编辑程序,当我使用“复制”按钮时遇到错误。如果从它复制到剪贴板内容的文本框为空,那么我得到“未处理ArgumentNullException”。我知道这是因为它复制文本的TextBox是空的。我想编写一个方法,如果TextBox为空,则禁用该按钮。以下是此按钮的代码:

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

感谢任何和所有帮助。如果我遗漏了更多细节,请告诉我,以便我可以添加它们。

3 个答案:

答案 0 :(得分:3)

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

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

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

答案 1 :(得分:2)

你应该检查null:

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

答案 2 :(得分:1)

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

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