C# program question
private void delete_Click(object sender, EventArgs e) { convertedText.Text = ""; }
private void copy_Click(object sender, EventArgs e)
{
if (convertedText.Text != "")
Clipboard.SetText(convertedText.Text);
convertedText.Text = Clipboard.GetText();
else... what to put here?
}
The program has two buttons (copy and delete) and one textbox. If I click the 'Copy' button, it copies the text from convertedText.Text without any problem. The 'delete' button also clears the textbox fine.
But if there's nothing in the textbox, the 'copy' butt开发者_开发知识库on still attempts to copy it which is causing an unexpected behaviour.
So, what code do I add to the 'else' statement...? What I want is that if the textbox has nothing in it, then the clipboard operation won't be used. How to do that?
Thanks in advance!
Don't add an else
clause, just have the if
by itself, e.g.
private void copy_Click(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(convertedText.Text))
{
Clipboard.SetText(convertedText.Text);
convertedText.Text = Clipboard.GetText();
}
}
Also, is there any reason why you're copying the text box text to the clipboard and then using the clipboard text to update the text box text? Unless I'm missing something, this should have no effect on the text box, so the code can be simpler:
private void copy_Click(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(convertedText.Text))
Clipboard.SetText(convertedText.Text);
}
Your error stems from the fact that you are missing some parentheses there:
if (convertedText.Text != "")
{
Clipboard.SetText(convertedText.Text);
convertedText.Text = Clipboard.GetText();
}
Only the first line after an if statement is considered to be part of what gets executed dependent on the evaluation of the if when you are omitting parentheses.
You could also return if the textbox does not have a value...
private void copy_Click(object sender, EventArgs e)
{
if (convertedText.Text.Equals(""))
return;
Clipboard.SetText(convertedText.Text);
convertedText.Text = Clipboard.GetText();
}
maybe you are missing brackets {
and }
if (convertedText.Text != ""){
Clipboard.SetText(convertedText.Text);
convertedText.Text = Clipboard.GetText();
}
else
Try putting
try
{
string foo = "bar" + 42;
}
catch
{
throw;
}
精彩评论