I'm creating a clipboard editing program and I encountered an error when I use the Copy button. If the text box from where it copies to the clipboard's contents are null, then I get a "ArgumentNullException was not handled". I know this is because the TextBox it copies the text from is empty. I want to write a method where if the TextBox is empty, then the button is disabled. Here is the code for this button:
// Copies the text in the text box to the clipboard.
private void copyButton_Click(object sender, EventArgs e)
{
Clipboard.SetText(textClipboard.Text);
}
Any and all help is appreciated. If I'm missing some more details please let me know so I can add them.
You have to initially set the button to be disabled.
Then you can use that code to detect the change in the text box:
private void textClipboard_TextChanged(object sender, EventArgs e)
{
copyButton.Enabled = textClipboard.Text.Length > 0;
}
You should check for 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
}
}
You could initially set the button.enabled to false, and add a KeyUp event to your textbox:
private void textClipboard_KeyUp(object sender, KeyEventArgs e)
{
copyButton.Enabled = !string.IsNullOrEmpty(textBox1.Text);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.