MessageBox中的C#自定义异常标题

时间:2016-02-22 01:42:53

标签: c# wpf exception messagebox

标题有点令人困惑,所以希望我能在这里解释得更好。如果出现错误,我想更改屏幕上弹出的MessageBox的标题,因为默认消息非常冗长,我更愿意为用户可以理解的错误提供更好的解释。

private void Load_Click(object sender, RoutedEventArgs e)
    {
        if (comboBox.SelectedItem.ToString() == "Department Staff")
        {
            try
            {
                DataTable dt = dataSource.DataTableQuery("SELECT * FROM DepartmentStaff");
                dataGrid.ItemsSource = dt.DefaultView;
            }
            catch (NullReferenceException ex)
            {
                MessageBox.Show("Unable To Connect To Database, Please Try Again Later.", ex.ToString());
            }

        }
        else
        {
            try
            {
                DataTable dt = dataSource.DataTableQuery("SELECT * FROM Department");
                dataGrid.ItemsSource = dt.DefaultView;
            }
            catch (NullReferenceException ex)
            {
                MessageBox.Show("Unable To Connect To Database, Please Try Again Later.", ex.ToString());
            }

        }

1 个答案:

答案 0 :(得分:4)

仔细查看Message.Show()参数:

Message.Show(text, caption); //the first one is text, the second one is caption.

第二个参数是标题(或标题),而第一个是消息。现在在你的使用中,你把你的异常消息(通常很长)作为标题,这就是为什么你得到"极长的啰嗦&#34 ; 标题(不是消息)。

MessageBox.Show("Unable To Connect To Database, Please Try Again Later.", ex.ToString());

不要这样做!相反,这样做:

MessageBox.Show("Unable To Connect To Database, Please Try Again Later. " +  ex.ToString(), "Error");

简单地说"错误"作为标题论点。

相关问题