0

我对 C# 非常陌生,并且正在使用 Winforms 进行我的研究项目。下面的代码没有做它的工作。当我的richComResults (richTextBox) 为空时,我希望出现一个消息框并说“没有什么要清除的!”,但它没有说出来,它显示的是/否对话框。

请你能指出我的错误吗?您的意见将不胜感激。谢谢你。

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)
            {
            }
        }
    }
4

2 回答 2

4

richComResults是你的RichTextBox控制,所以它可能不为空......你需要检查的是它的Text属性。它也可能不是 null,但它可能是空的(请记住,空字符串与 null 不同)。string.IsNullOrEmpty无论如何,您都可以用来测试这两种情况:

    if (string.IsNullOrEmpty(richComResults.Text))
    {
        MessageBox.Show("There is nothing to be cleared!");
    }
    else
    {
        ...
    }
于 2012-08-08T01:12:20.693 回答
0

检查richtextbox是否为空的另一种方法

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

            }
            else
            {
                MessageBox.Show("rich text box is not empty");
            }
于 2012-08-08T01:27:35.293 回答