0

I am very very new to C# and I am in the process of doing my project for my studies using Winforms. The below code is not doing its work. When my richComResults (richTextBox) is empty, I want a messageBox to appear and says "There is nothing to be cleared!", but it doesn't say it, it shows the Yes/No dialog.

Please could you be kind enough to point out my mistakes? Your input would be very much appreciated. Thank you.

private void btnComClearAll_Click(object sender, EventArgs e)
    {
        if (richComResults == null)
        {
            MessageBox.Show("There is nothing to be cleared!");
        }
        if (richComResults != null)
        {
            DialogResult dialogResult = MessageBox.Show("Are you sure you want to clear the results?", "Warning", MessageBoxButtons.YesNo);
            if (dialogResult == DialogResult.Yes)
            {
                richComResults.Clear();
            }
            else if (dialogResult == DialogResult.No)
            {
            }
        }
    }
merv
  • 331
  • 5
  • 25
  • You don't want to check richComResults, you want to check richComResults.Text. – Bob Horn Aug 08 '12 at 01:06
  • If you're using the RichTextBox that doesn't have the Text property, perhaps this can help: http://stackoverflow.com/questions/957441/richtextbox-wpf-does-not-have-string-property-text – Bob Horn Aug 08 '12 at 01:09
  • `null` is different than `String.Empty` or `""`. `null` means there is no value while `""` means that the strings value is empty – Liam McInroy Aug 08 '12 at 01:31

2 Answers2

4

richComResults is your RichTextBox control, so it's probably not null... What you need to check is its Text property. It will probably not be null either, but it might be empty (keep in mind that an empty string is not the same as null). You can use string.IsNullOrEmpty to test both cases anyway:

    if (string.IsNullOrEmpty(richComResults.Text))
    {
        MessageBox.Show("There is nothing to be cleared!");
    }
    else
    {
        ...
    }
Thomas Levesque
  • 286,951
  • 70
  • 623
  • 758
0

Another way to check whether richtextbox is empty or not

if (richComResults.Text== "")
            {
                MessageBox.Show("rich text box is empty");

            }
            else
            {
                MessageBox.Show("rich text box is not empty");
            }
user484458
  • 168
  • 3
  • 11